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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With