Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 理解'not'运算符的优先级_Python_String_Comparison - Fatal编程技术网

Python 理解'not'运算符的优先级

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:

我尝试在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: 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)