Python 理解'not'运算符的优先级
我尝试在Python中测试空字符串(空字符串应该是“Falsy”,因为它们在:)。但是,我使用了一点不同的语法,在以下比较中得到了奇怪的结果:Python 理解'not'运算符的优先级,python,string,comparison,Python,String,Comparison,我尝试在Python中测试空字符串(空字符串应该是“Falsy”,因为它们在:)。但是,我使用了一点不同的语法,在以下比较中得到了奇怪的结果: not(''); # result: True not('hello'); # result: False not('hello') == False; # result: True not('hello') == True; # result: True - how is this result possible? (False == True:
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)
谢谢你的回答 这里的优先级是
not('hello'==False)
'hello'
既不等于True
也不等于False
,因此'hello'==True
和'hello'==False
都是False
,然后被not
否定
>>> 'hello' == False
False
>>> 'hello' == True
False
>>> not ('hello' == True)
True
真实性并不等于真实。字符串可以是真实的(即,您可以决定它更像是“是”还是“否”),但同时不能等于布尔值(因为字符串是字符串,布尔值是布尔值)。重要的是要理解
不是是运算符,而不是函数。括号对表达式没有任何作用,下面是它的读取方式:
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
FWIW,()
和;
是非常多余的…not
否定布尔值。空字符串是假的。not Falsy是真的。-非空字符串是Thruthy,not truty是flase。not
不是函数-()是你自己做的。not(hello)=True
等于not(“hello”==True)