在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