Python中'if x in else'语句在Jupyter Notebook中失效问题排查
问题原因与解决建议
错误根源
你的if条件逻辑写法有误。Python中"sunny" or "lovely" in sitrep的执行顺序是先判断"sunny"的布尔值——非空字符串在布尔语境下永远为True,所以整个条件表达式直接返回True,完全不会去检查"lovely" in sitrep这部分。这就导致不管目标字符串里有没有指定关键词,代码都会执行if块的内容。
修正方案
有两种简洁的正确写法:
写法1:分别判断每个关键词
明确对每个关键词做in判断,再用or连接:
sitrep = "it is horrible weather" print("The sitrep is: " + sitrep) print(type(sitrep)) if "sunny" in sitrep or "lovely" in sitrep: print("sunny or lovely have been detected") else: print("neither has been detected")
写法2:用any()函数(适合关键词较多的场景)
把关键词放到列表里,用生成器表达式配合any()判断:
sitrep = "it is horrible weather" target_words = ["sunny", "lovely"] print("The sitrep is: " + sitrep) print(type(sitrep)) if any(word in sitrep for word in target_words): print("sunny or lovely have been detected") else: print("neither has been detected")
验证结果
修正后的代码运行后,会输出预期结果:
it is horrible weather <class 'str'> neither has been detected
内容的提问来源于stack exchange,提问作者e-driver1
相关产品推荐
相关产品推荐

