在python中,如何将两个变量与一个字符串进行比较?
如果a或b为空,我想打印一条消息 这是我的尝试在python中,如何将两个变量与一个字符串进行比较?,python,operators,Python,Operators,如果a或b为空,我想打印一条消息 这是我的尝试 a = "" b = "string" if (a or b) == "": print "Either a or b is empty" 但只有当两个变量都包含空字符串时,才会打印消息 仅当a或b为空字符串时,如何执行print语句 更明确的解决方案是: if a == '' or b == '': print('Either a or b is empty') 在这种情况下,还可以检查元组中的包含: if '' in (a
a = ""
b = "string"
if (a or b) == "":
print "Either a or b is empty"
但只有当两个变量都包含空字符串时,才会打印消息
仅当a或b为空字符串时,如何执行print语句 更明确的解决方案是:
if a == '' or b == '':
print('Either a or b is empty')
在这种情况下,还可以检查元组中的包含:
if '' in (a, b):
print('Either a or b is empty')
你可以这样做:
if ((not a) or (not b)):
print ("either a or b is empty")
因为bool(“”)
为False
当然,这相当于:
if not (a and b):
print ("either a or b is empty")
请注意,如果要检查两个是否都为空,可以使用运算符链接:
if a == b == '':
print ("both a and b are empty")
或者您可以使用:
if not any([a, b]):
print "a and/or b is empty"
第二个是低效的,因为需要创建一个元组,然后在其中执行搜索。
if not (a and b):
print "Either a or b is empty"
if not any([a, b]):
print "a and/or b is empty"