-1

I need to find if a string contains a phrase from a list, and print it.

For example:

my_phrases = ['Hello world', 'apple', 'orange', 'red car']

my_string = 'I am driving a red car'

The result should hopefully say that "a phrase or word has been found" and is "red car"

I found a way to do that with single words in a very clever way (found on another discussion):

def words_in_string(word_list, my_string):
   return set(word_list).intersection(my_string.split())

So

if words_in_string(word_list,my_string):
           print('a word has been found ')
for word in words_in_string(word_list,my_string):
           print(word)

it works if word_list is a list of single words, but it doesn't if I try to use phrases.

1
  • If you need to check for whole words, you will need a regex, see this Python demo. Commented Apr 13, 2021 at 18:25

1 Answer 1

0

Does this solve the issue:

my_phrases = ['Hello world', 'apple', 'orange', 'red car']

my_string = 'I am driving a red car'


for phrase in my_phrases:
    if phrase in my_string:
        print(phrase)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.