简体   繁体   中英

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

I have a list of words (ie):

['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?

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

One-Liner

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM