首页 > 解决方案 > python:在字符串末尾移动一个特定的单词

问题描述

我学习python,我做了一个不和谐的机器人。在“anivia”之后打印元素有一些困难。我不能说'texte'中是否有“anivia”,我可以数他,但我不知道如何在“anivia”之后打印元素,如果有人可以帮助我请:)

@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)

我可以用 z 数 9 个“anivia”,并且我想在所有 anivia 之后打印下一个元素(例如:“hello im anivia and i like anivia test”:and , test)。

谢谢你的帮助 :)

标签: pythonpython-3.xdiscord

解决方案


如果您熟悉正则表达式 (regex),这将变得非常简单:

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']

推荐阅读