[英]Python doesn't recognize -1 as False?
我最近編寫了一個Python程序,該程序使用:
if s.find('something'):
要么
if s.find('something')==True:
但在我使用之前,任何方法都無法正常工作
if s.find('something') >0
這是我可以在程序中獲得准確的True決定的唯一方法。
似乎-1結果未被識別為False。 成功的發現也不被認為是真實的。 因此,尋找-1(False)或正數> 0(True)是唯一對我有用的方法。
我做錯了什么? 這不是Python的工作方式,對嗎?
您正在錯誤地解釋find
的返回值。 該文檔指出:
str.find(sub[, start[, end]])
返回找到子字符串
sub
的字符串中的最低索引,這樣sub
包含在切片s[start:end]
。 可選參數start和end解釋為切片表示法。 如果未找到sub
則返回-1
。
在所有數字中,Python認為只有0為假; -1是正確的 。 當find
返回匹配開始處的索引,並且0是字符串的有效索引,如果未找到匹配項,則返回-1。
因此,您的代碼應*為:
if s.find('something') != -1:
要么
if s.find('something') >= 0:
盡管它們也不是最適合Python的語言,但是如果您僅想查看s
包含'something'
,請參閱下文。
現在,關於第二個示例: bool
常量False
比較等於0
:
>>> 0 == False
True
和bool
常數True
僅等於1
:
>>> 1 == True
True
>>> 2 == True
False
因此,表達式s.find('something') == True
將與s.find('something') == 1
完全等效; 和整個表達式將評估為True
僅當s
將形式的xsomethingxxxx
,具有匹配something
起始於第二字符(索引1)。
str.find
的文檔繼續以下注釋:
注意
僅當您需要知道
sub
的位置時,才應使用find()
方法。 要檢查sub
是否是子字符串,請使用in
運算符:>>> 'Py' in 'Python' True
因此,最適合您問題的Python形式為
if 'something' in s:
正如@myaut所建議的那樣,如果您需要 s
中'something'
的位置並希望它包含該值,則應改用str.index
,如果在substring
中未找到substring
,則將引發異常。
try:
position = s.index('something')
print("'something' found at", position)
except ValueError:
print(s, "does not contain the substring 'something'")
Python認為0
是False
,而不是-1
。
如您在Python文檔中所見,Python嘗試使用許多不同類型的False
值:
False
None
0
:任何數值類型的0
, 0L
, 0.0
, 0j
。 ''
, ()
, []
。 {}
。 您的直覺性觀點認為-1
在Python中應該為False
,這是有道理的,但這並不是Python的設計方式。 零和空在Python中是錯誤的。
如果只想檢查另一個字符串是否包含,請使用:
if 'something' in s:
print 'something in %s' % s
else:
print 'bad luck'
-1
作為錯誤代碼來自C,但這導致檢查返回值的意大利面條代碼。
Python有更可靠的報告錯誤的方法: 引發Exception 。 即str.index
做到這一點:
>>> 'abcde'.find('cd')
2
>>> 'abcde'.index('cd')
2
>>> 'abcde'.find('zx')
-1
>>> 'abcde'.index('zx')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
當然,要檢查字符串是否包含子字符串,應in
運算符中使用:
>>> 'ab' in 'abcde'
True
>>> 'zx' in 'abcde'
False
說到if
語句,您應該注意與boolean進行比較是個壞主意(例如,檢查PEP-8 )。
Python中的每種類型都定義了自己的規則,這些值被視為“ True”: 真值測試
驗證其布爾值是最快的方法;
bool(-1)
True
bool(0)
False
bool('')
False
等等,
你沒有做錯什么。
在python bool
繼承自int
。 False
為0
, True
為1
。 您可以嘗試int(True)
和int(False)
。 如果嘗試使用bool(0)
,則將獲得False
;但是,如果您編寫bool(-1)
或bool(1)
,則將始終獲得True
。 如果使用find
您將得到-1
因此您需要使用>= 0
。 您可以在'something'
找到'something'
'something else'
。
您可以if 'something' in s:
寫if 'something' in s:
。 我認為已棄用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.