我知道 .index()
将返回子字符串在 python 中的位置。
但是,我想要的是第 n 次找到子字符串所在的位置,这将像这样工作:
>> s = 'abcdefacbdea'
>> s.index('a')
0
>> s.nindex('a', 1)
6
>>s.nindex('a', 2)
11
有没有办法在 python 中做到这一点?
最佳答案
怎么样...
def nindex(mystr, substr, n=0, index=0):
for _ in xrange(n+1):
index = mystr.index(substr, index) + 1
return index - 1
观测值:为 str.index()
确实如此,nindex()
在未找到 substr 时引发 ValueError
。
关于Python索引不止一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3380654/