简体   繁体   中英

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

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

You got the logic backwards.

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

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM