How to check if multiple substrings appear together in a string
strings = ['I have a bird', 'I have a bag and a bird', 'I have a bag']
words = ['bird','bag']
I want to search for a string that contains both the bird and the bag in the list strings
, regardless of order. Thus, the result for only the second element in strings
should be true, and the rest should be false.
The output I want is:
False
True
False
words
does not need to be stored in a list and I know I regex
could do a similar thing, but I would rather use other ways than regex
because my words are Mandarin Chinese which requires some tricky regex usage than English.
source to share
Using the all () function would be the best option here, but the point does without a loop . Here is a solution using map / lambda function .
strings = ['I have a bird', 'I have a bag and a bird', 'I have a bag']
words = ['bird','bag']
map(lambda x: all(map(lambda y:y in x.split(),words)),strings)
:
[False, True, False]
However Naive solution for beginners:
for string in strings:
count_match=0
for word in words:
if word in string.split():
count_match+=1
if(count_match==len(words)):
print "True"
else:
print "False"
And the output will be:
False
True
False
source to share