Search code examples
pythonstringsubstring

Find the nth occurrence of substring in a string


This seems like it should be pretty trivial, but I am new at Python and want to do it the most Pythonic way.

I want to find the index corresponding to the n'th occurrence of a substring within a string.

There's got to be something equivalent to what I WANT to do which is

mystring.find("substring", 2nd)

How can you achieve this in Python?


Solution

  • Mark's iterative approach would be the usual way, I think.

    Here's an alternative with string-splitting, which can often be useful for finding-related processes:

    def findnth(haystack, needle, n):
        parts= haystack.split(needle, n+1)
        if len(parts)<=n+1:
            return -1
        return len(haystack)-len(parts[-1])-len(needle)
    

    And here's a quick (and somewhat dirty, in that you have to choose some chaff that can't match the needle) one-liner:

    'foo bar bar bar'.replace('bar', 'XXX', 1).find('bar')