Skip to content
Related Articles

Related Articles

Improve Article

Python String rindex() Method

  • Last Updated : 23 Aug, 2021
Geek Week

Python String rindex() method returns the highest index of the substring inside the string if the substring is found. Otherwise, it raises an exception.

Syntax: 

str.rindex(sub, start, end)

Parameters: 

  • sub : It’s the substring which needs to be searched in the given string.
  • start : Starting position where sub is needs to be checked within the string.
  • end : Ending position where suffix is needs to be checked within the string.

Note: If start and end indexes are not provided then by default it takes 0 and length-1 as starting and ending indexes where ending indexes is not included in our search.



Return:

Returns the highest index of the substring inside the string if substring is found. Otherwise it raises an exception. 

Errors and Exceptions: 

ValueError: This error is raised when the argument string is not found in the target string.

Example 1

input: text = 'geeks for geeks'
       result = text.rindex('geeks')
output: 10

input: text = 'geeks for geeks'
       result = text.rindex('ge')
output: 10

Python3




# Python code to demonstrate working of rindex()
text = 'geeks for geeks'
 
result = text.rindex('geeks')
print("Substring 'geeks':", result)

Output: 

Substring 'geeks': 10

Example 2 

Python3




# Python code to demonstrate error by rindex()
text = 'geeks for geeks'
 
result = text.rindex('pawan')
print("Substring 'pawan':", result)

Error: 

Traceback (most recent call last):
  File "/home/dadc555d90806cae90a29998ea5d6266.py", line 6, in 
    result = text.rindex('pawan')
ValueError: substring not found

Example 3

Python3




# Python code to demonstrate working of rindex()
# with range provided
quote = 'geeks for geeks'
 
# Substring is searched in ' geeks for geeks'
print(quote.rindex('ge', 2))
 
# Substring is searched in 0 to 10 range
print(quote.rindex('geeks', 0, 10))

Output: 

10
0

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :