How to use find() and replace() methods In Python
Python3
# Python3 code to demonstrate # Find last occurrence of substring # initializing string test_string = "GfG is best for CS and also best for Learning" # initializing target word tar_word = "best" # printing original string 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 result print ( "Index of last occurrence of substring is : " + str (res)) |
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" # Find all occurrences of the substring matches = re.finditer(tar_word, test_string) # Find the last occurrence by getting the index of the last match last_occurrence = - 1 for match in matches: last_occurrence = match.start() print ( "Index of last occurrence of substring is:" , last_occurrence) #This code is contributed by Edula Vinay Kumar Reddy |
Index of last occurrence of substring is: 28
Time complexity: O(n), where n is the length of the string
Auxiliary Space : O(n)
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 find the last occurrence of substring in string in Python.