Griffin Bender Griffin Bender - 5 days ago 6
Python Question

How to check a string for elements in an array in python 3.4

Lets say I have the following variables...

bad_words = ['bad0', 'bad1', 'bad2']
bad_string = "This string has bad1 in it."
bad_string2 = "This string is abcbad0xyz."
good_string = "This string is good!"


What's the best way to look through the strings for the 'bad words' and only print out the good string?

Example...

def check_words(string):
bad_words = ['bad0', 'bad1', 'bad2']
#this is where I need help...
#Return False if string contains any of the words in bad words
#Return True if string does not contain bad words.


bad_string = "This string has bad1 in it."
good_string = "This string is good!"

#call the check_words method by sending one of the strings
valid = check_words(bad_string) #I want this to return False

if valid:
print("Good string!")
else:
print("Bad string!")

#or...
valid = check_words(good_string) #I want this to return True

if valid:
print("Good string!")
else:
print("Bad string!")

Answer

This is pretty straight forward, iterate through the bad_words and check if word is in string, and return False if it is. After we check all the bad_words we can return True safely.

def check_words(string):
    bad_words = ['bad0', 'bad1', 'bad2']
    for word in bad_words:
        if word in string:
            return False
    return True