首页 > 解决方案 > 尝试在带有发誓的嵌入中插入,不适用于最后一个列表中的字符串

问题描述

我正在尝试制作一个城市词典命令,我正在用“[NSFW]”这个词替换脏话,尽管它仅在我将脏话放在列表的最后一部分时才有效。

我的代码:

nsfwdefine = ["swear1", "swear2","swear3"]

// there are headers I just didn't add them because it has my apikey.

async with ClientSession() as session:
    async with session.get(url, headers=headers, params=querystring) as response:
        r = await response.json()
        embed = discord.Embed(title=f"All result for {term}", description=None,color=0xff0000)
        embed.set_author(name=ctx.author.display_name, url="https://ass.com/", icon_url=ctx.author.avatar_url)
        definition = r['list'][0]['definition']
        embed.add_field(name=term, value=definition, inline=False)
        txt = str(definition)
        for y in nsfwdefine:
          x = re.sub(y, '[NSFW]', txt)
        print(x)

embed2=discord.Embed(title=f"All results for {term}", description=x)
embed2.add_field(name="Info",value=":warning: If your message contains the word [NSFW] then you need to rerun the defintion in a NSFW Channel.")

(await ctx.send(embed = embed2))

我不完全确定发生了什么,有人知道解决方案吗?

标签: pythonpython-3.xdiscord.py

解决方案


我不确定您为什么要使用,尽管您可以使用 string方法re.sub()来实现这一点。replace()

swears = ["swear1", "swear2", "swear3"]
sentence = "hello swear1 this is swear2 a sample swear3 sentence!"

for word in swears:
    sentence = sentence.replace(word, "[NSFW]")

print(sentence)

输出: hello [NSFW] this is [NSFW] a sample [NSFW] sentance!

运行代码片段


推荐阅读