Computer >> Computer tutorials >  >> Programming >> Python

How to find the nth occurrence of substring in a string in Python?


You can find the nth occurrence of a substring in a string by splitting at the substring with max n+1 splits. If the resulting list has a size greater than n+1, it means that the substring occurs more than n times. Its index can be found by a simple formula, length of the original string - length of last splitted part - length of the substring.

Example

def findnth(string, substring, n):
    parts = string.split(substring, n + 1)
    if len(parts) <= n + 1:
        return -1
    return len(string) - len(parts[-1]) - len(substring)
findnth('foobarfobar akfjfoobar afskjdf foobar', 'foobar', 2)

Output

This would give the output:

31

The n in this starts from 0. It is quite trivial to change that.