简体   繁体   中英

How do I compare two variables against one string in python?

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?

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')
if not (a and b):
    print "Either a or b is empty"

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")
if a == "" and b == "":
    print "a and b are empty"
if a == "" or b == "":
    print "a or b is empty"

Or you can use:

if not any([a, b]):
    print "a and/or b is empty"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM