0
這兩種方法之間有什麼區別?檢查空字符串的兩種方法之間的區別
if myString == ""
if not myString:
在詢問之前我讀了Most elegant way to check if the string is empty in Python?,但沒有說明它們的區別。
這兩種方法之間有什麼區別?檢查空字符串的兩種方法之間的區別
if myString == ""
if not myString:
在詢問之前我讀了Most elegant way to check if the string is empty in Python?,但沒有說明它們的區別。
這兩種方法都會告訴你,給出一個字符串對象foo
,無論它是一個空字符串或不:
>>> foo = ''
>>> foo == ''
True
>>> not foo
True
>>> foo = 'foo'
>>> foo == ''
False
>>> not foo
False
然而,給出的任意對象bar
,你會得到不同的結果:
>>> bar = [] # empty list
>>> bar == ''
False # isn't an empty string
>>> not bar
True # but is still empty
測試真實性適用於許多不同種類的物體(見the docs),所以not x
會告訴你,只要你有一個「空」對象,但x == ''
只會告訴你,你是否有一個空字符串。你需要哪些行爲將取決於你所處的形勢:
not
是整潔);== ''
;和not
。謝謝onrsharpe,真棒! –
我在詢問之前看過帖子,在那篇文章中,並沒有澄清他們的分歧。如果我錯了,請隨時糾正我。 –
@jonrsharpe試圖說這是錯誤的最後寫了 – The6thSense
@jonrsharpe,糾正了我的問題。感謝您的見解。謝謝。 –