How to use rindex() to find last occurrence of substring In Python

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




# Python3 code to demonstrate
# Find last occurrence of substring
# using rindex()
 
# 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))
 
# using rindex()
# Find last occurrence of substring
res = test_string.rindex(tar_word)
 
# print result
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

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

Similar Reads

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....

Using rfind() to find last occurrence of substring

...

Using lambda() with rlocate() function

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....

Using find() and replace() methods

...

Using reversed() function and index()

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....

Contact Us