Python | Ways to find nth occurrence of substring in a string

Given a string and a substring, write a Python program to find the nth occurrence of the string. Let’s discuss a few methods to solve the given task.

Method #1: Using re

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate 
# to find nth occurrence of substring
  
import re
  
# Initialising values
ini_str = "abababababab"
substr = "ab"
occurence = 4
  
  
# Finding nth occurrence of substring
inilist = [m.start() for m in re.finditer(r"ab", ini_str)]
if len(inilist)>= 4:
      
    # Printing result
    print ("Nth occurrence of substring at", inilist[occurence-1])
else:
    print ("No {} occurrence of substring lies in given string".format(occurence))

chevron_right


 
Method #2: Using find() method



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate 
# to find nth occurrence of substring
  
# Initialising values
ini_str = "abababababab"
sub_str = "ab"
occurence = 4
  
  
# Finding nth occurrence of substring
val = -1
for i in range(0, occurence):
    val = ini_str.find(sub_str, val + 1)
       
# Printing nth occurrence
print ("Nth occurrence is at", val)

chevron_right


 
Method #3: Using startswith() and list comprehension

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate 
# to find nth occurrence of substring
  
# Initialising values
ini_str = "abababababab"
substr = "ab"
occurence = 4
  
  
# Finding nth occurrence of substring
inilist = [i for i in range(0, len(ini_str))
            if ini_str[i:].startswith(substr)]
  
if len(inilist)>= 4:
      
    # Printing result
    print ("Nth occurrence of substring at", inilist[occurence-1])
else:
    print ("No {} occurrence of substring lies in given string".format(occurence))
         

chevron_right




My Personal Notes arrow_drop_up

Programming freaktech Enthusiast and have interest in learning new upcoming technologies

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : nidhi_biet



Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.