Python String rindex() Method

The Python string rindex() method searches a given string object's substring backwards. It returns the max index number or position of the substring(occurs last) in the given string. It raises a ValueError If the substring does not exist in the subject string.


string.rindex(substr, start, end)

This rindex() method accepts three parameters.

substr(required) This substring to be searched in subject string.
start(optional) It is an integer value specifying the index position to start the search. If not specified, the default value 0 is taken.
end(optional) It is an integer value specifying the index position where to end the search. If not specified, -1 value is taken, and mean full string length is searched
Return Value:

The highest index position of the occurrence of the string within another string. If the given string is not found, It raises a ValueError.

In the following example, the occurrence of 'i' is searched within the string, and the index always starts with 0. Hence it will return 17 the max index position as a result.


# Python example of the rindex() method.

str = "Nothing is impossible!!!"
result = str.rindex("i")




If no start and end arguments are assigned.


name = 'Tutorials Nation'
result = name.rindex('Nation')
print("Substring 'Nation' occurrence found at", result)



Substring 'Nation' occurrence found at 10

The following example checks, If the given string is found. If the substring is not found, the rindex() method raises the ValueError.


name = 'Tutorials Nation'
    result = name.rindex('web')
except ValueError:
    result = -1

if result != -1:
    print("The substring is found.")
    print("The substring is not found.") 



The substring is not found.