The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: The Builders

--

Chapters
00:00 Python - If String Contains A Word From A List Or Set
01:01 Accepted Answer Score 9
01:18 Answer 2 Score 1
02:02 Answer 3 Score 1
02:17 Thank you

--

Full question
https://stackoverflow.com/questions/2728...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #set

#avk47



ACCEPTED ANSWER

Score 9


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.




ANSWER 2

Score 1


Swear = ("curse", "curse", "curse") 
Userinput = str.lower(raw_input("Tell me about your day: "))

if any(Userinput.find(s)>=0 for s in Swear):
     print("Quit Cursing!")
else:
     print("That sounds great!")

Result:

Tell me about your day: curse
Quit Cursing!

Tell me about your day: cursing
That sounds great!

Tell me about your day: curses
Quit Cursing!

Tell me about your day: I like curse
Quit Cursing!

Using Regular Expression:

Pattern used is r"\bcurse[\w]*".

Swear = ("curse", "curse", "curse") 
Userinput = str.lower(raw_input("Tell me about your day: "))

if any(match.group() for match in re.finditer(r"\bcurse[\w]*", Userinput)) :
     print("Quit Cursing!")
else:
     print("That sounds great!")

finditer(pattern, string, flags=0)
    Return an iterator over all non-overlapping matches in the
    string.  For each match, the iterator returns a match object.

    Empty matches are included in the result.



ANSWER 3

Score 1


You can use sets, if only you want to check the existance of swear words,

a_swear_set = set(Swear)

if a_swear_set & set(Userinput.split()):
     print("Quit Cursing!")
else:
     print("That sounds great!")