在Python3教程中,声明“可以将比较结果或其他布尔表达式分配给变量。”给出的例子是:Python:使用'或'运算符比较字符串
>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'
'或'运算符在比较字符串时究竟做了什么?为什么选择了“特隆赫姆”?
在Python3教程中,声明“可以将比较结果或其他布尔表达式分配给变量。”给出的例子是:Python:使用'或'运算符比较字符串
>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'
'或'运算符在比较字符串时究竟做了什么?为什么选择了“特隆赫姆”?
当作为布尔处理,一个空字符串将返回False
和非空字符串将返回True
。
由于Python支持短路,因此在表达式a or b
中,如果a
为真,则不会评估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'
被返回。
or
返回它左侧的值,如果是true-ish,则返回右侧的值,否则返回右侧的值。
对于字符串,只有""
(空字符串)不是真的,ish,所有其他的都是。
所以
>>> "" or "Test"
"Test"
和
>>> "One" or "Two"
"One"
它不会做一个比较的。
啊,我明白了。短路?现在我感觉有点傻了 – uncreative
是的,它短路。 – RemcoGerlich
包容or
选择第一非falsy串(从检查从左到右),在这种情况下是'Trondheim'
>>> bool('')
False
>>> bool('Trondheim')
True
执行这种类型的检查时strip
字符串文字,因为它有时优选如果你不想选择空格,空格也是真的。
>>> bool(' ')
True
在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
,因此得出结果。
基本上,如果string1 == True,那么non_null = string1 else if string2 == True then non_null = string2 else if string3 == True then non_null = string3它停在string2,因为任何非空字符串在Python中都是true。 – bi0phaz3
@ bi0phaz3:“string”== True为false。你的意思是bool(string1)== True。 – RemcoGerlich
Python可以隐式抛出,我认为 – bi0phaz3