Python - Find index of Nth occurrence of search string in a string
Find index of Nth occurrence of a search search in the string
To find the index of Nth occurrence of substring in string in Python, call find() method on the string iteratively for N times with the index (+1) found in the previous iteration as start for searching.
The syntax to find the index of first occurrence of substring search
in the string x
after a specific start is
x.find(search, start)
Examples
1. Find index of Nth occurrence of "apple" in given string
In the following program, we take a string x
, and a search string search
. The values of x
and search
are such that x
contains search
. So, find() method must return the index of first occurrence of search
in x
.
The search is done in non-overlapping mechanism.
Python Program
x = 'apple is red. apple is good. apple is food.'
search = 'apple'
n = 2
start = x.find(search)
while start >= 0 and n > 1:
start = x.find(search, start+len(search))
n -= 1
print('Index :', start)
Output
Index : 14
Explanation
apple is red. apple is good. apple is food.
apple <- (n=2)th occurrence
0123.. ..13 is the index of nth occurrence
2. Find index of Nth occurrence of search string (Search Overlapping)
In the following program, we find the nth occurrence of search string search
int the string x
, in overlapping mechanism.
Python Program
x = 'bananabananabanana'
search = 'ana'
n = 4
start = x.find(search)
while start >= 0 and n > 1:
start = x.find(search, start+1)
n -= 1
print('Index :', start)
Output
Index : 9
Summary
In this tutorial of Python Examples, we learned how to find the index of Nth occurrence of a search string or substring in a string using str.find() method, with the help of well detailed examples.