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
  Help with to check an Input list data with a data read from an external source sacharyya 3 317 Mar-09-2024, 12:33 PM
Last Post: Pedroski55
  [solved] list content check paul18fr 6 614 Jan-04-2024, 11:32 AM
Last Post: deanhystad
  Function to count words in a list up to and including Sam Oldman45 15 6,403 Sep-08-2023, 01:10 PM
Last Post: Pedroski55
  Pulling Specifics Words/Numbers from String bigpapa 2 723 May-01-2023, 07:22 PM
Last Post: bigpapa
  How do I check if the first X characters of a string are numbers? FirstBornAlbratross 6 1,426 Apr-12-2023, 10:39 AM
Last Post: jefsummers
  check if element is in a list in a dictionary value ambrozote 4 1,879 May-11-2022, 06:05 PM
Last Post: deanhystad
  How to check if a list is in another list finndude 4 1,791 Jan-17-2022, 05:04 PM
Last Post: bowlofred
  Extract a string between 2 words from a text file OscarBoots 2 1,826 Nov-02-2021, 08:50 AM
Last Post: ibreeden
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 2,455 Aug-12-2021, 04:25 PM
Last Post: palladium
  Generate a string of words for multiple lists of words in txt files in order. AnicraftPlayz 2 2,756 Aug-11-2021, 03:45 PM
Last Post: jamesaarr

Forum Jump:

User Panel Messages

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