我尝试在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)谢谢你的回答!
发布于 2020-10-26 18:41:48
这里的优先级是not ('hello' == False)。'hello'既不等于True,也不等于False,所以'hello' == True和'hello' == False都是False,然后被not取反。
>>> 'hello' == False
False
>>> 'hello' == True
False
>>> not ('hello' == True)
True真实性并不等同于True。字符串可以是真的(即您可以决定它是"yes“还是"no"),但同时不等于布尔值(因为字符串是字符串,而布尔值是布尔值)。
发布于 2020-10-26 18:42:08
重要的是要理解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) == Truehttps://stackoverflow.com/questions/64535443
复制相似问题