How to check if a string contains a word from a list

1.2k Views Asked by At

I want the user to input lyrics to the program (this will later be extended to searching a website, but i dont currently want help with that) and the program will tell me if the inputted info contains a word from a list.

banned_words = ["a","e","i","o","u"] #This will be filled with swear words

profanity = False

lyrics = input ("Paste in the lyrics: ")
for word in lyrics:
    if word in banned_words:
        print("This song says the word "+word)
        profanity = True

if profanity == False:
    print("This song is profanity free")

This code just outputs 'This song is profanity free.'

1

There are 1 best solutions below

0
jpp On

There are several ideas I'd recommend:

  • Split by whitespace using str.split.
  • Use set for O(1) lookup. This is denoted by {} instead of [] used for lists.
  • Wrap your logic in a function. This way you can simply return as soon as a swear word is reached. You then no longer need else statements.
  • Using a function means you don't need to set a default variable and then reassign if applicable.
  • Catch upper and lower case words using str.casefold.

Here's an example:

banned_words = {"a","e","i","o","u"}

lyrics = input("Paste in the lyrics: ")

def checker(lyrics):
    for word in lyrics.casefold().split():
        if word in banned_words:
            print("This song says the word "+word)
            return True
    print("This song is profanity free")
    return False

res = checker(lyrics)