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

我是研究僧i 提交于 2021-02-07 18:01:58

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!