How to Use String rindex() Method in PythonPython Basics


Rindex() finds the position of the last occurrence of a substring in a given string. If not found, it returns an error message.

Example

#!/usr/bin/python3
str1 = "nice to meet you, George! have a nice day.....!!!"
str2 = "nice"
str3 = 'days'

# Find the index of last occurrence
print (str1.rindex(str2))

# Not found, return error
print (str1.rindex(str3))

Output:

33
Traceback (most recent call last):
  File "main.py", line 10, in 
    print (str1.rindex(str3))
ValueError: substring not found

Syntax

str.rindex(substr, start = 0, end = len(string))

Parameters

Name Description
substr Substring to be searched in the string
start Optional, starting index of the search (inclusive)
end Optional, ending index of the search (exclusive)

Return Value

It returns the index of position where the substring appears for the last time.

© 2024 Cheerlearn.com, all rights reserved. Privacy Policy | Contact Us