【问题标题】:How do I compare two variables against one string in python?如何在python中将两个变量与一个字符串进行比较?
【发布时间】:2012-06-25 16:59:14
【问题描述】:

如果 a 或 b 为空,我想打印一条消息。

这是我的尝试

a = ""
b = "string"

if (a or b) == "":
    print "Either a or b is empty"

但只有当两个变量都包含空字符串时才会打印消息。

如何仅当 a 或 b 为空字符串时才执行打印语句?

【问题讨论】:

    标签: python operators


    【解决方案1】:

    更明确的解决方案是:

    if a == '' or b == '':
        print('Either a or b is empty')
    

    在这种情况下,您还可以检查元组中的包含:

    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】:

      你可以这样做:

      if ((not a) or (not b)):
         print ("either a or b is empty")
      

      因为bool('') 是假的。

      当然,这相当于:

      if not (a and b):
         print ("either a or b is empty")
      

      请注意,如果您想检查 both 是否为空,可以使用运算符链接:

      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】:

          或者你可以使用:

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

          【讨论】:

            猜你喜欢
            • 2017-03-02
            • 1970-01-01
            • 1970-01-01
            • 2016-09-08
            • 1970-01-01
            • 2016-02-27
            • 2018-01-23
            • 2017-10-25
            • 2015-10-03
            相关资源
            最近更新 更多