Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python index more than once

I know that .index() will return where a substring is located in python. However, what I want is to find where a substring is located for the nth time, which would work like this:

>> s = 'abcdefacbdea'
>> s.index('a')
0
>> s.nindex('a', 1)
6
>>s.nindex('a', 2)
11

Is there a way to do this in python?

like image 791
John Howard Avatar asked Dec 16 '22 22:12

John Howard


1 Answers

How about...

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

Obs: as str.index() does, nindex() raises ValueError when the substr is not found.

like image 67
Lord British Avatar answered Jan 01 '23 20:01

Lord British