如果a或b为空,我想打印一条消息。
这是我的尝试
a = ""
b = "string"
if (a or b) == "":
print "Either a or b is empty"
但只有当两个变量都包含空字符串时才会打印消息。
如果a或b是空字符串,我该如何执行print语句?
答案 0 :(得分:6)
更明确的解决方案是:
if a == '' or b == '':
print('Either a or b is empty')
在这种情况下,您还可以检查元组中的包含:
if '' in (a, b):
print('Either a or b is empty')
答案 1 :(得分:4)
if not (a and b):
print "Either a or b is empty"
答案 2 :(得分:3)
你可以这样做:
if ((not a) or (not b)):
print ("either a or b is empty")
由于bool('')
为假。
当然,这相当于:
if not (a and b):
print ("either a or b is empty")
请注意,如果您想检查两者是否为空,则可以使用操作员链接:
if a == b == '':
print ("both a and b are empty")
答案 3 :(得分:2)
if a == "" and b == "":
print "a and b are empty"
if a == "" or b == "":
print "a or b is empty"
答案 4 :(得分:1)
或者您可以使用:
if not any([a, b]):
print "a and/or b is empty"