Skip to main content
 首页 » 编程设计

Python string.find() 给出错误 "slice indices must be integers or None or have an __index__ method"

2025年05月04日9EasonJim

我正在尝试在 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,这将起作用。

如果它是一个字符串对象(错误表明是这种情况),那么第二个参数是它应该开始搜索的位置。该位置必须是整数或None 或具有__index__ 方法的对象。 drug 是一个字符串,因此会出现错误。

你可能想要的是:

if row[1].find(drug) != -1: 

但最好使用 in 进行简单的子字符串检查:

if drug in row[1]: