test_string = ("this is a test")
test_list = [dog, cat, test, is, water]
How do I see if 'this' or 'is' or 'a' or 'test' is in test_list?
test_string = ("this is a test")
test_list = [dog, cat, test, is, water]
How do I see if 'this' or 'is' or 'a' or 'test' is in test_list?
Use str.split to split the string and use any to see if any of the words in the string are in your list:
test_string = ("this is a test")
test_list = ["dog", "cat", "test", "is","water"]
print(any(x in test_list for x in test_string.split()))
In [9]: test_string = ("this is a test")
In [10]: test_string.split()
Out[10]: ['this', 'is', 'a', 'test'] # becomes a list of individual words
You can use any
for this
inlist = any(ele in test_list for ele in test_string.split())
inlist
will be True or False, depending on whether or not it's in the list.
Example:
>>test_string = ("this is a test")
>>test_list = ['dog', 'cat', 'water']
>>inlist = any(ele in test_string for ele in test_list)
>>print inlist
False
>>test_string = ("this is a test")
>>test_list = ['dog', 'cat', 'is', 'test' 'water']
>>inlist = any(ele in test_string for ele in test_list)
>>print inlist
True
What you're asking is just whether the set intersection is nonempty.
>>> set(test_string.split(' ')).intersection(set(test_list))
set(['test', 'is'])
One option is regex, eg
import re
# Test string
test_string = 'this is a test'
# Words to be matched
test_list = ['dog', 'cat', 'test', 'is', 'water']
# Container for matching words
yes = []
# Loop through the list of words
for words in test_list:
match = re.search(words, test_string)
if match:
yes.append(words)
# Output results
print str(yes) + ' were matched'
#['test', 'is'] were matched