检查字符串是否在列表中

Wad*_*dbo 2 python input list

我见过很多此类问题的解决方案,但我找不到我正在寻找的解决方案。

例如:

text = ['hi', 'hello', 'hey']
user_input = input('Enter something: ')

for word in user_input:
    if word in text:
        print('Hi')
    else:
        print('Bye')
Run Code Online (Sandbox Code Playgroud)

如果是user_input“嗨,那里”,它会给我回复

Bye
Bye
Bye
Bye
Bye
Bye
Bye
Bye
Run Code Online (Sandbox Code Playgroud)

如何检查user_input列表(文本)中是否至少有一个单词?

Sou*_*hra 6

你可以试试这个:

text = ['hi', 'hello', 'hey']
user_input = input('Enter something: ')

for word in user_input.split(" "):
    if word in text:
        print('Hi')
    else:
        print('Bye')
Run Code Online (Sandbox Code Playgroud)

另外一个选择:

text = ['hi', 'hello', 'hey']
user_input = input('Enter something: ')

flag = "Y"
for word in user_input.split(" "):
    if word in text:
        print('Matched String:', word)
    else:
        flag = "N"

if flag == "N":
    print("Unmatched String Exists")
Run Code Online (Sandbox Code Playgroud)