Python索引不止一次

Joh*_*ard 3 python string indexing substring

我知道.index()将返回子串在python中的位置.但是,我想要的是找到子串在第n次的位置,这将是这样的:

>> s = 'abcdefacbdea'
>> s.index('a')
0
>> s.nindex('a', 1)
6
>>s.nindex('a', 2)
11
Run Code Online (Sandbox Code Playgroud)

有没有办法在python中执行此操作?

Lor*_*ish 7

怎么样...

def nindex(mystr, substr, n=0, index=0):
    for _ in xrange(n+1):
        index = mystr.index(substr, index) + 1
    return index - 1
Run Code Online (Sandbox Code Playgroud)

Obs:同样str.index(),当找不到substr时nindex()引发ValueError.