String rindex() in python

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

Syntax:

str.find(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 indxes 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.

Examples:

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

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

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

CODE 1

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Substring 'geeks': 10

CODE 2

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Error:

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

CODE 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

10
0


My Personal Notes arrow_drop_up

pawanasipugmailcom

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.