【问题标题】:Python: Compare strings with 'or' operatorPython:使用“或”运算符比较字符串
【发布时间】:2016-10-22 16:46:42
【问题描述】:

在 Python3 教程中,声明“可以将比较结果或其他布尔表达式分配给变量”。给出的例子是:

>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'

在比较字符串时,'or' 运算符究竟做了什么?为什么选择“特隆赫姆”?

【问题讨论】:

  • 基本上,如果 string1 == True then non_null = string1 else if string2 == True then non_null = string2 else if string3 == True then non_null = string3 它停在 string2 因为任何非空字符串都是真的在 Python 中。
  • @bi0phaz3: "string" == True 是 false。你的意思是 bool(string1) == True。
  • 我认为 Python 可以隐式转换

标签: python string python-3.x boolean boolean-logic


【解决方案1】:

包含or 选择第一个非假字符串(从左到右检查),在本例中为'Trondheim'

>>> bool('')
False
>>> bool('Trondheim')
True

在对strip 执行此类检查时,有时最好使用字符串文字,因为如果您不打算选择空格,那么空格也是真实的。

>>> bool(' ')
True

【讨论】:

    【解决方案2】:

    当被视为布尔值时,空字符串将返回False,非空字符串将返回True

    由于 Python 支持短路,在表达式 a or b 中,如果 a 为 True,则不会计算 b

    在您的示例中,我们有'' or 'Trondheim' or 'Hammer Dance'

    这个表达式是从左到右计算的,所以第一个被计算的是'' or 'Trondheim',或者换句话说False or True,它返回True。接下来,Python 尝试评估 'Trondheim' or 'Hammer Dance',而后者又变成 True or 'Hammer Dance'。由于前面提到的短路,因为左边的对象是 True,'Hammer Dance' 甚至不会被评估为 True,这就是返回 'Trondheim' 的原因。

    【讨论】:

      【解决方案3】:

      or 如果为真则返回左侧的值,否则返回右侧的值。

      对于字符串,只有""(空字符串)不是真的,其他都是。

      所以

      >>> "" or "Test"
      "Test"
      

      >>> "One" or "Two"
      "One"
      

      它根本不做比较。

      【讨论】:

      • 啊,我明白了。短路?现在我觉得有点傻
      • 是的,它短路了。
      【解决方案4】:

      non_null 的赋值中,or 的比较是按顺序计算的,也就是说:

      if string1:
          non_null = string1
      elif string2:
          non_null = string2
      elif string3:
          non_null = string3
      else:
          non_null = False
      

      但是,在您的示例中,string1 是一个空字符串,其计算结果为 False(您可以通过在提示中输入 if not '':print("Empty") 来检查)。

      由于string2 不为空,因此被评估为True,它被分配给non_null,因此是结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-28
        • 2013-08-23
        • 1970-01-01
        • 2012-10-05
        • 2019-06-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多