Python:检测多字符串是否未存在的代码错误原因排查
问题分析:为什么关键词都存在时仍触发错误提示?
先还原下你的场景:
你定义了字符串:
message = "The boy Akash is studying in 9th class at Boys school"
想检测boy、class、school这三个单词是否都在字符串里,只要有一个没出现就输出错误提示,但你写的代码:
if('boy' or 'class' or 'school' not in message): print = "Please check if you have filled all data"
哪怕三个关键词全在message里,还是会触发错误,这到底是为啥?
错误根源:条件判断的逻辑完全走偏了
Python里的布尔表达式是从左到右依次判断的,咱们拆解下你写的条件:('boy' or 'class' or 'school' not in message)
- 首先判断
'boy':在Python中,非空字符串会被判定为True - 一旦第一个表达式为
True,整个or连接的表达式就直接返回True了,后面的'class'和'school' not in message根本不会被执行!
也就是说,你的这个if条件永远为True,不管message里有没有目标关键词,都会执行错误提示的代码。
正确的写法有两种
写法一:逐个检查每个关键词是否缺失
把每个关键词的not in判断用or连接,这样只要有一个关键词不在字符串里,就触发错误:
message = "The boy Akash is studying in 9th class at Boys school" if 'boy' not in message or 'class' not in message or 'school' not in message: print("Please check if you have filled all data")
写法二:用all()函数更简洁(推荐)
把需要检查的关键词放到列表里,用all()函数判断所有关键词是否都在字符串中,取反后就是“有至少一个关键词缺失”的情况:
message = "The boy Akash is studying in 9th class at Boys school" required_words = ['boy', 'class', 'school'] if not all(word in message for word in required_words): print("Please check if you have filled all data")
这种写法的好处是后面要加/改关键词,直接修改required_words列表就行,扩展性拉满~
额外小提醒:注意大小写问题
你的原字符串里是Boys(首字母大写),而你检查的是小写的boy,不过Python的in判断是大小写敏感的哦!如果需要忽略大小写,可以把字符串转成小写后再判断:
if not all(word in message.lower() for word in required_words): print("Please check if you have filled all data")
内容的提问来源于stack exchange,提问作者wanderors
相关产品推荐
相关产品推荐

