Python | Find last occurrence of substring
Last Updated :
17 Apr, 2023
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 find the last occurrence of substring in string in Python.
Using rindex() to find last occurrence of substring
rindex() method returns the last occurrence of the substring if present in the string. The drawback of this function is that it throws the exception if there is no substring in the string and hence breaks the code.
Python3
test_string = "GfG is best for CS and also best for Learning"
tar_word = "best"
print ( "The original string : " + str (test_string))
res = test_string.rindex(tar_word)
print ( "Index of last occurrence of substring is : " + str (res))
|
Output
The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28
Using rfind() to find last occurrence of substring
rfind() is the alternate method to perform this task. The advantage that this function offers better than the above method is that, this function returns a “-1” if a substring is not found rather than throwing the error.
Python3
test_string = "GfG is best for CS and also best for Learning"
tar_word = "best"
print ( "The original string : " + str (test_string))
res = test_string.rfind(tar_word)
print ( "Index of last occurrence of substring is : " + str (res))
|
Output
The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28
Using lambda() with rlocate() function
Here we are using the more_itertools library that provides us with rlocate() function that helps us to find the last occurrence of the substring in the given string.
Python3
import more_itertools as m
test_string = "GfG is best for CS and also best for Learning"
tar_word = "best"
pred = lambda * x: x = = tuple (tar_word)
print ( "The original string : " +
str (test_string))
res = next (m.rlocate(test_string, pred = pred,
window_size = len (tar_word)))
print ( "Index of last occurrence of substring is : " +
str (res))
|
Output:
The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28
Using find() and replace() methods
Python3
test_string = "GfG is best for CS and also best for Learning"
tar_word = "best"
print ( "The original string : " + str (test_string))
x = test_string.count(tar_word)
i = 1
while (i<x):
test_string = test_string.replace(tar_word, "*" * len (tar_word), 1 )
i + = 1
res = test_string.find(tar_word)
print ( "Index of last occurrence of substring is : " + str (res))
|
Output
The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28
Time Complexity: O(n), where n is length of test_string.
Auxiliary Space: O(1)
Using the re module:
The re (regular expression) module in Python allows you to search for patterns in strings. In this approach, we use the finditer function from the re module to find all occurrences of the substring in the string. The finditer function returns an iterator yielding MatchObject instances that have information about the search, such as the start and end indices of the match.
We can then use a for loop to iterate through the matches and keep track of the index of the last occurrence by updating the last_occurrence variable whenever we find a match. Finally, we print the index of the last occurrence.
Python3
import re
test_string = "GfG is best for CS and also best for Learning"
tar_word = "best"
matches = re.finditer(tar_word, test_string)
last_occurrence = - 1
for match in matches:
last_occurrence = match.start()
print ( "Index of last occurrence of substring is:" , last_occurrence)
|
Output
Index of last occurrence of substring is: 28
Time complexity: O(n), where n is the length of the string
Auxiliary Space : O(n)
Using reversed() function and index()
Step-by-step approach:
- Reverse the test_string and tar_word
- Use the index() method to get the first occurrence of the reversed tar_word in the reversed test_string.
- Calculate the index of the last occurrence of the tar_word by subtracting the index from the length of the test_string and the length of the tar_word.
Python3
test_string = "GfG is best for CS and also best for Learning"
tar_word = "best"
res = len (test_string) - test_string[:: - 1 ].index(tar_word[:: - 1 ]) - len (tar_word)
print ( "Index of last occurrence of substring is : " + str (res))
|
Output
Index of last occurrence of substring is : 28
Time complexity: O(n) where n is the length of the string
Space complexity: O(1)
Using the numpy:
Algorithm:
- Initialize the test string and target word.
- Create an empty numpy array to store the indices of all occurrences of the target word.
- Iterate over all possible substrings of length equal to the length of the target word in the test string. For each substring, check if it matches the target word or not. If the substring matches the target word, append the index of the first character of the substring to the numpy array.
- Check if any occurrences of the target word were found or not. If the numpy array is not empty, set the result to be the last element of the array (i.e., the index of the last occurrence of the target word in the test string). Otherwise, set the result to -1 (indicating that the target word was not found in the test string).
- Print the original string and the index of the last occurrence of the target word (or -1 if the target word was not found).
Below is the implementation of the above approach:
Python3
import numpy as np
test_string = "GfG is best for CS and also best for Learning"
tar_word = "best"
indices = np.array([i for i in range ( len (test_string) - len (tar_word) + 1 )
if test_string[i:i + len (tar_word)] = = tar_word])
if indices.size > 0 :
res = indices[ - 1 ]
else :
res = - 1
print ( "The original string : " + str (test_string))
print ( "Index of last occurrence of substring is : " + str (res))
|
Output:
The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28
Time Complexity: O(n * m), where n is the length of the test string and m is the length of the target word. This is because the list comprehension iterates over all possible substrings of length m in the test string, which takes O(n * m) time in the worst case.
Space Complexity: O(k), where k is the number of occurrences of the target word in the test string. This is because the indices of all occurrences of the target word are stored in a numpy array, which takes O(k) space. The rest of the variables used in the code take constant space.
Using rpartition() method
- Define the string and target word to find last occurrence of substring.
- Use the rpartition() method to split the string at the last occurrence of the target word.
- If the length of split list is 1, print that the substring was not found in the string.
- Otherwise, calculate the index of the last occurrence of the target word using the length of the original string, the length of the third element in the split list (which contains the characters after the last occurrence of the target word), and the length of the target word.
- Print the index of the last occurrence of the target word.
Python3
test_string = "GfG is best for CS and also best for Learning"
tar_word = "best"
print ( "The original string : " + str (test_string))
split_list = test_string.rpartition(tar_word)
if len (split_list) = = 1 :
print ( "Substring not found in string" )
else :
res = len (test_string) - len (split_list[ 2 ]) - len (tar_word)
print ( "Index of last occurrence of substring is : " + str (res))
|
Output
The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28
Time Complexity: O(n), where n is the length of the input string.
Auxiliary Space: O(1), as no extra is used.
Similar Reads
Python - Mid occurrence of K in string
Given a String, the task is to write a Python program to extract the mid occurrence of a character. Input : test_str = "geeksforgeeks is best for all geeks", K = 'e' Output : 10 Explanation : 7 occurrences of e. The 4th occurrence [mid] is at 10th index. Input : test_str = "geeksforgeeks is best for
6 min read
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 - Slice from Last Occurrence of K
Sometimes, while working with Python Strings, we can have a problem in which we need to perform the task of performing characters stripping on the last occurrence of element. This can have applications in which data is involved. Lets discuss certain ways in which this task can be performed. Method #
3 min read
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. 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.findite
4 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
Find the Index of a Substring in Python
Finding the position of a substring within a string is a common task in Python. In this article, we will explore some simple and commonly used methods to find the index of a substring in Python. Using str.find() The find() method searches for the first occurrence of the specified substring and retur
3 min read
Python - Maximum occurring Substring from list
Sometimes, while working with Python strings, we can have a problem in which we need to check for maximum occurring substring from strings list. This can have application in DNA sequencing in Biology and other application. Let's discuss certain way in which this task can be performed. Method 1 : Usi
6 min read
Python - Maximum Consecutive Substring Occurrence
Sometimes, while working with Python, we can have a problem in which we must check for substrings occurring in consecutive repetition. This can have applications in data domains. Let us discuss a way in which this task can be performed. Method #1: Using max() + re.findall() A combination of the abov
5 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
Longest String in list - Python
We are given a list of strings, and our task is to find the longest string present in the list. If there are multiple strings with the maximum length, we should return the first one that appears. For example, given a = ["alpha", "gamma", "epsilon", "delta"], the longest string is "epsilon". Let's di
3 min read