![](/img/trans.png)
[英]Python - slice indices must be integers or None or have an __index__ method
[英]Python string.find() giving error “slice indices must be integers or None or have an __index__ method”
我正在嘗試在Python中進行簡單的子字符串匹配,盡管我記得昨晚它運行良好,但是從早上開始,這段代碼給出了以下錯誤。 這似乎是一個已知的錯誤,有人可以建議為什么會發生嗎?
if string.find(row[1],drug) != -1:
print "abstract id = ", row[0],"Drug found=", drug
錯誤:
File "./substring.py", line 31, in <module>
if string.find(row[1],drug) != -1:
TypeError: slice indices must be integers or None or have an __index__ method
這里row[1]
和drug
都是簡單的字符串。
什么是string
?
如果它是模塊string
這將起作用。
如果它是一個字符串對象(錯誤表明是這種情況),則第二個參數是應該開始搜索的位置。 該位置必須是整數或None
或者是具有__index__
方法的對象。 drug
是一個字符串,因此會出現錯誤。
您可能想要的是:
if row[1].find(drug) != -1:
但最好使用in
簡單的字符串檢查:
if drug in row[1]:
嘗試使用row[1].find(drug)
代替string.find(row[1], drug)
row[1].find(drug)
。 .find()
方法將為您提供字符串首次出現的索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.