Home > Enterprise >  Python - How to check if multiple words in string in a list
Python - How to check if multiple words in string in a list

Time:10-10

I have this code:

intents = ['hello world', 'random string']

phrase = input(Enter your message: )

if phrase in intents:
    print('Found')

How can I check if phrase in intents without typing the exact strings in intents, If it's only one word it's easy but multiple words it's not working like that:

Enter your message: hello world this python
>>> Found

CodePudding user response:

You got the logic backwards.

for intent in intents:
    if intent in phrase:
        print('Found')
        break

CodePudding user response:

For this example you can just switch your logic around instead of checking for phrase in intents, check if intents in phrase

ie:

intents = ['hello world', 'random string']

phrase = input(Enter your message: )

for intent in intents:
  if intent in phrase:
    return True 

this is assuming the input is always larger than the intent,

you could add a check for the length

basically check if the smaller str is in the larger one, not the other way around.

I think you could also do some fancy trickery with any

like

is_in = any([i in phrase for i in intents]   [j in intents for j in phrase])
  • Related