-7
我想了解一段代碼,它搜索文本文件中的字符串。這是什麼意思?這是否像「假」?在Python中,「等於負1」是什麼意思?
if x.find('string1') != -1:
if x.find('string2') == -1 and x.find('string3') == -1:
return file
break
我想了解一段代碼,它搜索文本文件中的字符串。這是什麼意思?這是否像「假」?在Python中,「等於負1」是什麼意思?
if x.find('string1') != -1:
if x.find('string2') == -1 and x.find('string3') == -1:
return file
break
從str.find()
method documentation:
返回-1 子是找不到的。
所以第一if
條件測試,如果string1
在x
被發現;如果是,則返回值其他將比-1
。第二個if
條件測試如果兩個字符串是而不是存在於x
(因爲只有-1
返回兩個str.find()
調用)。
它真的應該使用成員測試(in
運營商),而不是:從未達到
if 'string1' in x and 'string2' not in x and 'string3' not in x:
return file
的break
的return
後。
謝謝,非常翔實的答案。 –
你的downvotes留言'RTFM',我把它引用你在這裏:https://docs.python.org/2/library/string.html它說:「返回最低索引在s找到子字符串子這樣該子文件完全包含在s [start:end]中。**在失敗時返回-1 ** –
@MartinCowie:並且您找到了錯誤的文檔,因爲它在'string'模塊中描述了不推薦使用的函數,而問題中的代碼使用'str.find()'方法(取代了棄用的函數)。行爲的描述可能是正確的,但要注意這樣的微妙之處! –