我有一个字符串消息
message = "The boy Akash is studying in 9th class at Boys school"
我想检查是否没有单词boy
或class
或school
,如果
any of those are not present it should show a error message.
if('boy' or 'class' or 'school' not in message):
print = "Please check if you have filled all data"
但是当我尝试这样做时,即使所有关键字都出现了,它也显示错误。哪里可能错了。请帮助
答案 0 :(得分:2)
大概您必须分别列出每个表达式:
if "boy" not in message or "class" not in message or "school" not in message:
print = "Please check if you have filled all data"
您还可以在此处使用正则表达式,以便使用单词边界进行可能更可靠的匹配:
match1 = re.search(r'\bboy\b', message)
match2 = re.search(r'\bclass\b', message)
match3 = re.search(r'\bschool\b', message)
if not match1 or not match2 or not match3:
print = "Please check if you have filled all data"
答案 1 :(得分:2)
这不起作用,因为您写的不是您的意思。
考虑代码段:
if 'boy':
print("There's a boy here")
如果运行它,您将得到:
>>> There's a boy here!
这是因为默认情况下,python将所有非空字符串都视为True
。
因此,要修复代码,您需要:
if('boy' not in message or 'class' not in message or 'school' not in message):
print = "Please check if you have filled all data"
或等效地:
for word in ['boy', 'class', 'school']:
if word not in message:
print = "Please check if you have filled all data"
答案 2 :(得分:1)
您的错误是什么?
您的语法应为:
if ('boy' not in message) or ('class' not in message) or ('school' not in message) :
print("Please check if you have filled all data")
如果您的条件带有多个表达式,则必须使用逻辑运算符(or,and)分隔每个表达式,如上所述,但是对于更复杂的决策结构,例如:
if ( (x < 2) and (y > 5) ) or (z == 0):
print("")
请注意print语句-您试图将字符串分配给变量print
,而不是使用print
函数将字符串作为参数。由于print
关键字是作为标准库函数保留的,因此您不应将其用作变量。