Python | Ways to find nth occurrence of substring in a string
Last Updated : 07 Apr, 2023
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 ini_str = "abababababab" substr = "ab" occurrence = 4 inilist = [m.start() for m in re.finditer(r "ab" , ini_str)] if len (inilist)> = 4 : 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
ini_str = "abababababab" sub_str = "ab" occurrence = 4 val = - 1 for i in range ( 0 , occurrence): val = ini_str.find(sub_str, val + 1 ) 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
ini_str = "abababababab" substr = "ab" occurrence = 4 inilist = [i for i in range ( 0 , len (ini_str)) if ini_str[i:].startswith(substr)] if len (inilist)> = 4 : 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) |
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)) |
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)
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