Python Forum
how to check if string contains ALL words from the list?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how to check if string contains ALL words from the list?
#1
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
Reply
#2
Use the keyword in to check if something is in a sequence.
Loop through each item you want to check is in the string.
Reply
#3
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
Reply
#4
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)
Reply
#5
This is a good place for a comprehension.

>>> all([x in some_string for x in some_list])
True
Reply
#6
(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.
Reply
#7
Thank you :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Function to count words in a list up to and including Sam Oldman45 13 607 Feb-18-2021, 10:22 AM
Last Post: perfringo
  Replacing a words' letters in a string cananb 2 351 Dec-01-2020, 06:33 PM
Last Post: perfringo
  Trying to find first 2 letter word in a list of words Oldman45 7 804 Aug-11-2020, 08:59 AM
Last Post: Oldman45
  check if letters in a words Vimart 4 767 Aug-10-2020, 09:59 PM
Last Post: deanhystad
  Check text contains words similar to themes/topics (thesaurus) Bec 1 513 Jul-28-2020, 04:17 PM
Last Post: Larz60+
  item from a line to list however when i print the line instead of words i get letters Sutsro 5 692 Apr-22-2020, 02:39 PM
Last Post: deanhystad
  I want to filter out words with one letter in a string (pig latin translator) po0te 1 606 Jan-08-2020, 08:02 AM
Last Post: perfringo
  How to check if user entered string or integer or float?? prateek3 5 6,992 Dec-21-2019, 06:24 PM
Last Post: DreamingInsanity
  How do you replace a word after a match from a list of words in each line of a file? vijju56 1 1,273 Oct-17-2019, 03:04 PM
Last Post: baquerik
  how to seperate words from string zarize 2 651 Aug-29-2019, 08:23 AM
Last Post: zarize

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020