检查字符串是否在列表中

时间:2020-09-28 07:23:22

标签: python list input

我已经看到许多解决此类问题的方法,但我找不到真正想要的解决方法。

例如:

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

for word in user_input:
    if word in text:
        print('Hi')
    else:
        print('Bye')

如果user_input在“那里”,它将带我回来

Bye
Bye
Bye
Bye
Bye
Bye
Bye
Bye

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

2 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

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

for word in user_input.split(" "):
    if word in text:
        print('Hi')
    else:
        print('Bye')

另一个选项:

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

答案 1 :(得分:0)

好吧,我不是Python开发人员,但我可以看到您的user_input正在逐字母进行迭代。

查看此article