-2
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?

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287

4 Answers4

0

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
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

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
Parker
  • 8,539
  • 10
  • 69
  • 98
0

What you're asking is just whether the set intersection is nonempty.

>>> set(test_string.split(' ')).intersection(set(test_list))
set(['test', 'is'])
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
0

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
tagoma
  • 3,896
  • 4
  • 38
  • 57