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


In this article, we are going to find out how to find the nth occurrence of a substring in a string in Python.

The first approach is by using the split() method. We have to define a function with arguments as string, substring, and the integer n. By dividing at the substring with max n+1 splits, you may locate the nth occurrence of a substring in a string.

If the size of the resultant list is higher than n+1, the substring appears more than n times. The length of the original string minus the length of the last split segment equals the length of the substring.

Example

In the example given below, we are taking a string and a substring as input and we are finding the nth occurrence of the substring in the string using split() method 

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)
   
string = 'foobarfobar akfjfoobar afskjdf foobar'
print("The given string is")
print(string)

substring = 'foobar'
print("The given substring is")
print(substring)

res = findnth(string,substring,2)
print("The position of the 2nd occurence of the substring is")
print(res)

Output

The output of the above example is as follows −

The given string is
foobarfobar akfjfoobar afskjdf foobar
The given substring is 34. How to find the nth occurrence of substring in a string in Python
foobar
The position of the 2nd occurence of the substring is
31

Using find() method

The second approach is by using the find() method. This method is performed the number of occurrences times and the final result is returned.

Example

In the example given below, we are taking a string and substring as input and we are finding the nth occurrence of the substring in the string 

string = 'foobarfobar akfjfoobar afskjdf foobar'

print("The given string is")
print(string)

substring = 'foobar'
print("The given substring is")
print(substring)
n = 2
res = -1
for i in range(0, n):
   res = string.find(substring, res + 1)
print("The position of the 2nd occurence of the substring is")
print(res)

Output

The output of the above example is given below −

The given string is
foobarfobar akfjfoobar afskjdf foobar
The given substring is
foobar
The position of the 2nd occurence of the substring is
16

Updated on: 07-Dec-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements