Python Forum

Full Version: how to check if string contains ALL words from the list?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys,

How can i check if string contains all words from the list?

some_string = 'there is a big apple, but i like banana more than orange'


some_list = ['apple', 'banana', 'orange']
It should return True
Use the keyword in to check if something is in a sequence.
Loop through each item you want to check is in the string.
well, first of all it should be dynamic, because the string will differ each time.

I tried this:
some_string = 'there is a big apple, but i like banana more than orange'
some_list = ['apple', 'banana', 'orange']

for word in some_list:
    if word in some_string:
        print(True)
in that case output was:
Output:
True True True
but i need to get return one True or one False
Flip the logic and check if the word is not in the string return false
outside of the loop return True (because it never found an item that was not in the list)
This is a good place for a comprehension.

>>> all([x in some_string for x in some_list])
True
(Jul-22-2020, 05:21 PM)bowlofred Wrote: [ -> ]This is a good place for a comprehension.

Unless they are trying to learn how to figure it out themselves and just need a push in the right direction.
Thank you :)