问题
I would like to print a message if either a or b is empty.
This was my attempt
a = ""
b = "string"
if (a or b) == "":
print "Either a or b is empty"
But only when both variables contain an empty string does the message print.
How do I execute the print statement only when either a or b is an empty string?
回答1:
The more explicit solution would be this:
if a == '' or b == '':
print('Either a or b is empty')
In this case you could also check for containment within a tuple:
if '' in (a, b):
print('Either a or b is empty')
回答2:
if not (a and b):
print "Either a or b is empty"
回答3:
You could just do:
if ((not a) or (not b)):
print ("either a or b is empty")
Since bool('')
is False.
Of course, this is equivalent to:
if not (a and b):
print ("either a or b is empty")
Note that if you want to check if both are empty, you can use operator chaining:
if a == b == '':
print ("both a and b are empty")
回答4:
if a == "" and b == "":
print "a and b are empty"
if a == "" or b == "":
print "a or b is empty"
回答5:
Or you can use:
if not any([a, b]):
print "a and/or b is empty"
来源:https://stackoverflow.com/questions/11193782/how-do-i-compare-two-variables-against-one-string-in-python