Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - If string contains a word from a list or set

Tags:

python

string

set

I have searched quite thoroughly and have not found a suitable answer. I am new to Python/Programming, so I appreciate any advice I can get:

I am trying to search user input strings for certain key words. For example, we'll say filtering out profanity. From my research, I have been able to make the following dummy example:

Swear = ("curse", "curse", "curse") #Obviously not typing actual swear words, created a set
Userinput = str.lower(input("Tell me about your day: "))

if Userinput in Swear:
     print("Quit Cursing!")
else:
     print("That sounds great!")

Using the above, if the user enters an exact word form the set as their entire string, it will print "quit cursing"; however, if the user enters "curses" or "I like to say curse" it will print "That sounds great!"

Ultimately what I need is to be able to search the entire string for a key word, not an exact match of the entire string. Ex: "I went to the park and felt like screaming curses" should return true for a match.

like image 310
MoJo2015 Avatar asked Dec 25 '22 01:12

MoJo2015


1 Answers

Swear = ["curse", "curse", "curse"]

for i in Swear:
    if i in Userinput:
        print 'Quit Cursing!'

You should read up on the differences between lists and tuples.

like image 147
caleb.breckon Avatar answered Dec 27 '22 16:12

caleb.breckon