检查多个字符串是否在另一个字符串中

时间:2019-07-05 19:39:01

标签: python-3.x loops

我正在创建一个聊天机器人,该机器人寻找特定术语以做出相关响应,但我一直在努力寻找从字符串中查找关键字的方法。

我已经尝试使用word in strwhile True: user = input("what's up?") if "sad" or "unhappy" or "depressed" in user: print("oh that's quite sad") else: print("that's good") ,但是我可能在其中的某个地方出现了问题。

{{1}}

无论我键入什么内容,它都会不断返回“哦,这真的很可悲”。

1 个答案:

答案 0 :(得分:0)

解决方案1:

while True:
    user = input("what's up?")
    if "sad" in user or "unhappy" in user or "depressed" in user:
        print("oh that's quite sad")
    else:
        print("that's good")

解决方案2:使用any

预先定义字符串并使用它:

mylist = ["sad","unhappy","depressed"]
while True:
    user = input("what's up?")
    if any([x in user for x in mylist]):
        print("oh that's quite sad")
    else:
        print("that's good")