-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.

rahlf23
  • 8,869
  • 4
  • 24
  • 54

1 Answers1

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)
Matiiss
  • 5,970
  • 2
  • 12
  • 29