fff
fff

Reputation: 111

How do I tell if a list of strings are found within a larger string?

I have a list of words (i.e.):

['bad', 'good', 'smart']

that I need to find which lines in a file that contain all those words within that line. I've tried:

for line in file_text: 
    if [w for w in list] in line:
        print(line) 

However I get the following error:

TypeError: 'in <string>' requires string as left operand, not list

What is an easy pythonic way of doing this?

Upvotes: 0

Views: 45

Answers (2)

Swastik Padhi
Swastik Padhi

Reputation: 1909

One-Liner

for line in file_text:
    [line for w in list if w in line and w == 'smart']

Upvotes: 0

Reut Sharabani
Reut Sharabani

Reputation: 31339

I think you want to use all (or any):

>>> lst = ["the", "fox", "brown"]
>>> sentence = "the quick brown fox jumps over the lazy dog"
>>> all(word in sentence for word in lst)
True

Upvotes: 3

Related Questions