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.

+3


source to share


5 answers


strings = ['I have a bird', 'I have a bag and a bird', 'I have a bag']
words = ['bird','bag']


for string in strings:
  stringlist = string.split()
  word1 , word2 = words
  if word1 in stringlist and word2 in stringlist:
    print(True)
  else:
    print(False)

      

Result



False True False

+1


source


List comprehension will work in conjunction with the function all

:

[all([k in s for k in words]) for s in strings]

      



This leads to the following example:

[False, True, False]

      

+5


source


It's him:

for substring in strings:
    k = [ w for w in words if w in substring ]
    print (len(k) == len(words) )

      

0


source


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

      

0


source


For a variable number of words without using the split function.

strings = ['I have a bird', 'I have a bag and a bird', 'I have a bag']
words = ['bird','bag']

 for string in strings:
    print(all(word in string for word in words))

      

0


source







All Articles