Python String - rindex() Method
The Python rindex() method is used to find out the index number for last occurrence of specified character(s) in the given string. This method is very similar to rfind() method. Only difference is that rfind() method returns -1 when character(s) is not found in the string and rindex() method gives exception error.
This method has two optional parameters also which can be used to specify starting point and end point within the string for this operation. Default values are start and end of the string.
Syntax
string.rindex(value, start, end)
Parameters
value |
Required. value of the character(s) which need to be searched in the string. |
start |
Optional. An integer specifying start position of search. default value is 0. |
end |
Optional. An integer specifying end position of search. default value is end of the string. |
Return Value
Returns the index number of last occurrence of the specified character(s) in the given string.
Example: rindex() method when value is present
In the example below, rindex() method is used to find out the index number for last occurrence of specified character(s) in the given string.
MyString = "Python is a programming language and learning Python is fun." print(MyString.rindex("Python")) print(MyString.rindex("Python", 0, 10))
The output of the above code will be:
46 0
Example: rindex() method when value is not present
The rindex() method raises exception when the specified character(s) is not present in the string.
MyString = "Python is a programming language and learning Python is fun." print(MyString.rindex("Python", 10, 20))
The output of the above code will be:
Traceback (most recent call last): File "Main.py", line 2, in <module> print(MyString.rindex("Python", 10, 20)) ValueError: substring not found
❮ Python String Methods