Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Count Occurance of Substring in a List of Strings - Python
Next article icon

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

Last Updated : 07 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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. 

Get Nth occurrence of a substring in a String using regex

Here, we find the index of the ‘ab’ character in the 4th position using the regex re.finditer()

Python3




import re
 
# Initialising values
ini_str = "abababababab"
substr = "ab"
occurrence = 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[occurrence-1])
else:
  print ("No {} occurrence of substring lies in given string".format(occurrence))
 
 

Output:

Nth occurrence of substring at 6

Get Nth occurrence of a substring in a String using find() method 

Here, we find the index of the ‘ab’ character in the 4th position using the str.find().

Python3




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

Output:

Nth occurrence is at 6

Get Nth occurrence of a substring in a String using startswith()  

Here, we find the index of the ‘ab’ character in the 4th position using the str.startwith().

Python3




# Initialising values
ini_str = "abababababab"
substr = "ab"
occurrence = 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[occurrence-1])
else:
  print ("No {} occurrence of substring lies in given string".format(occurrence))
    
 
 

Output:

Nth occurrence of substring at 6

Get Nth occurrence of a substring in a String using split()

Here, we find the index of the ‘ab’ character in the 4th position using the split().

Python3




def solve(s, str, n):
    sep = s.split(str, n)
    if len(sep) <= n:
        return -1
    return len(s) - len(sep[-1]) - len(str)
 
print('length: ', len('dellGeeks asusfor geeksforgeeksdell'))
print("position", solve('dellGeeks asusfor geeksforgeeksdell', 'dell', 2))
 
 

Output:

length:  35 position 31

The time complexity of the given code is O(n), where n is the length of the input string s.

The space complexity of the code is O(n), where n is the length of the input string s. 

Using the count() method:

Approach:

Use the count() method to find the total number of occurrences of the substring in the given string.
If the count is less than the given nth occurrence, return -1.
Else, use a loop to find the nth occurrence of the substring and return its index.

Python3




def find_nth_occurrence_1(s, sub, n):
    count = s.count(sub)
    if count < n:
        return -1
    else:
        index = -1
        for i in range(n):
            index = s.find(sub, index+1)
        return index
my_string = "hello world, how are you doing today? I hope you are doing well."
my_substring = "doing"
my_occurrence = 2
result = find_nth_occurrence_1(my_string, my_substring, my_occurrence)
print(result)
 
 
Output
53

Time Complexity: O(n)
Auxiliary Space: O(1)

METHOD 6: Using loop and counter

APPROACH:

This Approach tells how to find the index of the nth occurrence of a given substring within a given string. The approach used is a simple iteration over the string and checking whether the current substring matches the given substring. If it does, then the occurrence count is incremented. Once the count reaches the desired occurrence, the current index is returned. If no nth occurrence is found, then the function returns -1.

ALGORITHM:

1.Initialize counter as 0
2.Using a loop, search for the substring in the given string, and increase the counter every time the substring is found
3.If the counter is equal to the required occurrence, return the index of the last found substring
4.If the substring is not found enough times, return -1

Python3




def find_nth_occurrence(ini_str, substr, occurrence):
    count = 0
    for i in range(len(ini_str)):
        if ini_str[i:i+len(substr)] == substr:
            count += 1
            if count == occurrence:
                return i
    return -1
 
ini_str = "abababababab"
substr = "ab"
occurrence = 4
 
print(find_nth_occurrence(ini_str, substr, occurrence))
 
 
Output
6

Time complexity: O(n*m) where n is the length of the initial string and m is the length of the substring
Auxiliary Space: O(1)



Next Article
Count Occurance of Substring in a List of Strings - Python
author
garg_ak0109
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python - All occurrences of substring in string
    A substring is a contiguous occurrence of characters within a string. Identifying all instances of a substring is important for verifying various tasks. In this article, we will check all occurrences of a substring in String. Using re.finditer()re.finditer() returns an iterator yielding match object
    3 min read
  • Python - Ways to Count Number of Substring in String
    Given a string s, determine the number of substrings that satisfy certain criteria. For example we are given a string s="hellohellohello" we need to count how many time the substring occur in the given string suppose we need to find the substring "hello" so that the count becomes 3. We can use metho
    2 min read
  • Python program to find the occurrence of substring in the string
    Given a list of words, extract all the indices where those words occur in the string. Input : test_str = 'geeksforgeeks is best for geeks and cs', test_list = ["best", "geeks"] Output : [2, 4] Explanation : best and geeks occur at 2nd and 4th index respectively. Input : test_str = 'geeksforgeeks is
    4 min read
  • Python | Get the string after occurrence of given substring
    The problem involves getting the string that is occurring after the substring has been found. Let's discuss certain ways in which this task can be performed using Python. Using partition()To extract the portion of a string that occurs after a specific substring partition() method is an efficient and
    3 min read
  • Count Occurance of Substring in a List of Strings - Python
    To count the occurrences of a particular substring in a list of strings in Python, we can use several methods. In this article, we are going to explore different methods to count the existence of a particular substring in a given list. Using sum() and Generator ExpressionThis method uses a generator
    3 min read
  • Python - All occurrences of Substring from the list of strings
    Given a list of strings and a list of substring. The task is to extract all the occurrences of a substring from the list of strings. Examples: Input : test_list = ["gfg is best", "gfg is good for CS", "gfg is recommended for CS"] subs_list = ["gfg", "CS"] Output : ['gfg is good for CS', 'gfg is reco
    5 min read
  • Python | Get the starting index for all occurrences of given substring
    Given a string and a substring, the task is to find out the starting index for all the occurrences of a given substring in a string. Let's discuss a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python3 code to demonstrate # to find all occurrences of substring in #
    3 min read
  • Get Second Occurrence of Substring in Python String
    We are given a string and a substring, and our task is to find the index of the second occurrence of that substring within the string. This means we need to identify not just if the substring exists, but where it appears for the second time. For example, if we have a string like "hello world, hello
    2 min read
  • Python | Find last occurrence of substring
    Sometimes, while working with strings, we need to find if a substring exists in the string. This problem is quite common and its solution has been discussed many times before. The variation of getting the last occurrence of the string is discussed here. Let's discuss certain ways in which we can fin
    8 min read
  • How to Find Index of a Substring in Python
    In Python, sometimes we need to know where a certain substring appears in a string. To do this, we can find the index (or position) of that substring. The index tells us where the substring is located. Let’s look at some simple ways to find the index of a substring in a string. Using find() methodTh
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences