【问题标题】:Understanding precedence of `not` operator [duplicate]了解“not”运算符的优先级[重复]
【发布时间】:2020-10-26 10:35:48
【问题描述】:

我试图在 Python 中测试空字符串(空字符串应该是“Falsy”,因为他们写的是:How to check if the string is empty?)。但是我使用了一些不同的语法,并在以下比较中得到了奇怪的结果:

not(''); # result: True

not('hello'); # result: False

not('hello') == False; # result: True

not('hello') == True; # result: True - how is this result possible? (False == True: result must be False)

谢谢你的回答!

【问题讨论】:

  • FWIW,() 和 ; 是非常多余的......
  • not 否定布尔值。空字符串是 Falsy。不假是真的。 - 非空字符串是 Thruthy,不是 Truthy 是 flase。 not 没有功能 - ( ) 是你做的。 not (hello) == True 等于 not ( "hello" == True)

标签: python string comparison


【解决方案1】:

了解not 是一个运算符,而不是一个函数,这一点很重要。括号对表达式没有任何作用,它的读取方式如下:

not('hello') == True
# is the same as
not 'hello' == True
# which is the same as
not ('hello' == True)
# which is equivalent to 
not False
# which is 
True

它的计算结果与上面的表达式相同(与 'hello' == False 是 False 的原因相同。

使用not 强制执行优先级的正确方法是这样做

(not something) == True

【讨论】:

    【解决方案2】:

    这里的优先级是not ('hello' == False)。 'hello' 既不等于True 也不等于False,所以'hello' == True 和'hello' == False 都是False,然后被not 否定。

    >>> 'hello' == False
    False
    >>> 'hello' == True
    False
    >>> not ('hello' == True)
    True
    

    真实不等于等于True。字符串可以是 truthy(即您可以决定它更像是“是”还是“否”),但同时不能 等于 布尔值值(因为字符串是字符串,布尔值是布尔值)。

    【讨论】:

      猜你喜欢
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-09
      • 1970-01-01
      • 2015-10-07
      • 2016-06-17
      相关资源
      最近更新 更多