Daniel Agafonov
Daniel Agafonov

Reputation: 49

Comparing Strings using Python

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

I am trying to test to see if a string contains a certain key phrase. If the string contains something like, "Why Hello THeRe" then it must satisfy the if statement.

The code returns General Kenobi correctly, however, I want to have good code practice and do not understand why the list of words (HelloThere = ["Hello There", "Hello there", "hello there"]) only works when it's in this certain order and number. If for example I just have it as Hello There = ["Hello There"] and test for that, it won't work.

Upvotes: 2

Views: 101

Answers (1)

Samwise
Samwise

Reputation: 71454

You're testing the lowercased version of the message (.lower()) so the variants with uppercase letters can never match. The point of using .lower() in the first place is to avoid having to do any of this -- just test the lowercase phrase against the lowercased message so you can ignore capitalization entirely.

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

If you did have multiple phrases to check, it'd be more simple to use any:

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

Upvotes: 1

Related Questions