Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中,如何将两个变量与一个字符串进行比较?_Python_Operators - Fatal编程技术网

在python中,如何将两个变量与一个字符串进行比较?

在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为空,我想打印一条消息

这是我的尝试

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"