Home > Back-end >  Finding if List in Input()
Finding if List in Input()

Time:10-11

I'm attempting to find out when a list is in someone's input, here's the code:

Sad = ['sad','broken','depressed','sadness','grief',]

Input = input("Hi ").strip()

if Sad in Input:
    print("Word Found")
else:
    print("Word Not Found")

It works when you have one of the words in the list alone, but when it's a sentence including the word it returns as false.

CodePudding user response:

You're close, it's the reverse: if Input in Sad: you're trying to find an element, Input, in the Sad list ;)

If you want it to work with sentences in Input, you'll have to update your logic:

  1. Split Input into a list of word
  2. Loop on each word
  3. See if the word is present in Sad
Sad = ['sad','broken','depressed','sadness','grief',]


# split(" ") will split the string that is given as an input
# into a list of strings, using " " as a separator.
Input = input("Hi ").strip().split(" ")

for word in in Input:
    if word in Sad:
        print("Word {} Found".format(word)
    else:
        print("Word {} Not Found".format(word)

You can make this even easier using sets:


Sad = {'sad','broken','depressed','sadness','grief'}
Input = set(input("Hi ").strip().split(" "))
matching_words = Input & Sad

if matching_words:
    print("Some words found:", matching_words)
else:
    print("No words found)
  • Related