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

Sometimes, we want to find the nth occurrence of substring in a string with Python.

In this article, we’ll look at how to find the nth occurrence of substring in a string with Python.

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

To find the nth occurrence of substring in a string with Python, we can use a loop to find it.

For instance, we write:

def find_nth(haystack, needle, n):
    start = haystack.find(needle)
    while start >= 0 and n > 1:
        start = haystack.find(needle, start + len(needle))
        n -= 1
    return start


index = find_nth("foofoofoofoo", "foofoo", 2)
print(index)

to define the find_nth function that searches the haystack string for the needle.

And we want to find the nth occurrence of it.

In the function, we call haystack.find with needle to find the index of the first occurrence of needle.

If start is bigger than or equal to 0 and n is bigger than 1, then we start the while loop to use haystack.find(needle, start + len(needle)) to update start until n becomes 0.

Finally, we return start which is the first index of the nth occurrence of the needle.

Therefore, index is 6.

Conclusion

To find the nth occurrence of substring in a string with Python, we can use a loop to find it.