使用Python比较字符串

使用Python比较字符串,python,discord,discord.py,Python,Discord,Discord.py,我试图测试字符串是否包含某个关键短语。如果字符串包含类似“Why Hello THeRe”的内容,那么它必须满足If语句的要求 代码正确地返回了General Kenobi,但是,我希望有良好的代码实践,并且不理解为什么单词列表(HelloThere=[“Hello There”,“Hello There”,“Hello There”])仅在按此特定顺序和数字时才起作用。例如,如果我只是把它作为Hello There=[“Hello There”]进行测试,它就不会工作。您正在测试消息的小写版本

我试图测试字符串是否包含某个关键短语。如果字符串包含类似“Why Hello THeRe”的内容,那么它必须满足
If语句的要求


代码正确地返回了General Kenobi,但是,我希望有良好的代码实践,并且不理解为什么单词列表(
HelloThere=[“Hello There”,“Hello There”,“Hello There”]
)仅在按此特定顺序和数字时才起作用。例如,如果我只是把它作为
Hello There=[“Hello There”]
进行测试,它就不会工作。

您正在测试消息的小写版本(
.lower()
),因此带有大写字母的变体永远不会匹配。首先,使用
.lower()
的目的是避免执行任何操作——只需根据小写消息测试小写短语,就可以完全忽略大小写

HelloThere = ["Hello There", "Hello there", "hello there"]
for word in HelloThere:
    if (message.content.lower().count(word) > 0) and (message.author.id != 712885407993561169):
        await message.channel.send("General Kenobi")
如果要检查多个短语,则使用
any
会更简单:

if "hello there" in message.content.lower() and message.author.id != 712885407993561169:
    await message.channel.send("General Kenobi")

我不明白你的问题。在前一种情况下,
hellother
是一个
列表
,而在后一种情况下,它是一个
str
。用于。。。在
中,循环在每种情况下的工作方式明显不同。为什么会这样,因为我想了解这种工作方式不幸的是,堆栈溢出格式不适合解释这一点,但任何介绍性Python教程都会有所帮助。
phrases = {"hello there", "you are a bold one"}
if message.author.id != 712885407993561169 and any(
    p in message.content.lower() for p in phrases
):
    await message.channel.send("General Kenobi")