Python Find Nth Occurrence of Char in a String


In Python, how would you find the Nth occurrence of a character (or substring) in a string? Yes, this also works for a substring.

We can write a custom function to do this. If its not found the function will return negative one. If either the strg or the char or both are empty strings, it returns negative one. You are looking for char inside strg. We also want to find the Nth occurrence of it. We want to know where inside strg we find char.

def findnth(strg, char, n):
    if len(char) == 0:
        return -1
    start = strg.find(char)    # use built-in find method to get FIRST occurrence, if any
    while start >= 0 and n > 1:
        start = strg.find(char, start + len(char))
        n -= 1
    return start

The find method returns the first occurrence of the character or set of characters. The index is zero-based, meaning that it starts with zero, not one. If the characters or set of characters are not found at all, the find method returns negative one (-1). The find method takes two arguments. The first argument is just the string you are looking for. We can call that the substring, or the needle that’s in the haystack. The second argument is the index of the starting position. If you want to start at the beginning, you start at zero, which is the first character, since it is zero-based.

# find the second occurrence of "a" in "foo bar cat" 
# and return the position number
findnth('foo bar cat', 'a', 2)

This returns 9. The second ‘a’ is in cat. Since the index is zero-based, the a in cat is in position 9. Note that the ‘f’ in ‘foo bar cat’ is in position zero and spaces are characters too.

SQL Server

If you need to do a similar parsing operation in T-SQL in SQL Server, have a look at our post here called SQL Find Nth Occurrence of Char in a String.

Microsoft Excel

If you want to do the same thing in Microsoft Excel, have a look at our post called Excel Find Nth Occurrence of Char in a String. This post uses the Excel FIND and SUBSTITUTE functions.

Leave a comment

Your email address will not be published. Required fields are marked *