guiguilecodeur
guiguilecodeur

Reputation: 457

python:Move a specific word at the end of a string

i learn python and i do a discord bot. I have some difficulties to print the element after "anivia". i cant say if there is "anivia" in the 'texte' and i can count him but i don't know how to print the element after "anivia", if someone can help me please :)

@bot.command()
async def counter(ctx, *champion):
    champion = " ".join(champion)
    url = "https://u.gg/lol/champions/"
    counter = "/counter"
    uurl = url + champion + counter
    await ctx.send(uurl)

    import urllib.request
    with urllib.request.urlopen(uurl) as response:
        texte = response.read()
    if ("anivia" in str(texte)):
        print("Le mot existe !")
    else:
        print("Le mot n'existe pas!")
    test = str(texte)

    z = test.count('anivia')
    print(z)

I can count 9 "anivia" with z and i want to print the next element after all the anivia (example: " hello i m anivia and i like anivia test": and, test).

Thanks for your help :)

Upvotes: 2

Views: 184

Answers (3)

guiguilecodeur
guiguilecodeur

Reputation: 457

yeah, the those solution works with strings (i tried too with regex) but


    do_print = False
    splitted = test_string.split()
    for word in splitted:
        # print(word)

        if do_print:
            do_print = False
        if word == "anivia":
            do_print = True
    
    test_string = str(texte)

    do_print = False
    splitted = test_string.split()
    for word in splitted:
        # print(word)

        if do_print:
            do_print = False
            # print(word)
        if word == "champion_id":
            do_print = True`` 

on the first case i have the ("on" and the "jungle") but with my str(texte), that's doesn't fonction :S.
 If someone knows why, the 2 test_strings are "strings" 

 ^^ ty for your answers :)

Upvotes: 1

ricekab
ricekab

Reputation: 650

If you're familiar with regular expressions (regex), this becomes very simple:

import re

# This pattern will capture the first word that comes after "anivia"
pattern = r'anivia (\w+)'

# Using this string as our example input
example_string = "anivia first anivia second and finally anivia third"

results = re.findall(pattern, example_string)

print(results)  # Output: ['first', 'second', 'third']

Upvotes: 2

Chiorean Tudor
Chiorean Tudor

Reputation: 308

Here is an approach that uses an auxiliary variable to mark when the next word needs to be printed.

test_string = "Hello, I am anivia on mid or anivia jungle"

do_print = False
splitted = test_string.split()
for word in splitted:
    if do_print:
        do_print = False
        print(word)
    if word == "anivia":
        do_print = True

Output:

on
jungle

Upvotes: 1

Related Questions