Python rindex() method is used to find the highest index (or the last occurrence) of a substring within a string. If the substring is not found, it raises a ‘ValueError’.
This method is the same as rfind(), but the primary difference between rindex() and rfind() lies in their behavior when the substring is not found: rindex() raises a ValueError, while rfind() returns -1.
Syntax
string.rindex(substring, start, end)
Parameters
- substring(required): It’s the substring that needs to be searched in the given string.
- start(optional): Starting position where the substring needs to be checked within the string. (Default is 0)
- end(optional): It is the ending index within the string where the search ends.
Return Value
It returns the highest substring index in the main string; if that substring is not found, it throws an exception.
Visual Representation
Example 1: How to Use String rindex() Method
txt= "Hello I Love AppDividend"
print("Index of Love: ",txt.rindex("Love"))
print("Index of I: ",txt.rindex("I"))
print("Index of AppDividend: ",txt.rindex("AppDividend"))
print("Index of Appdividend: ",txt.rindex("Appdividend"))
Output
Index of Love: 8
Index of I: 6
Index of AppDividend: 13
ValueError: substring not found
The output indicates that the index for ‘AppDividend‘ is 13. However, since the index for ‘Appdividend‘ is not found due to case sensitivity, it raises a ValueError.
Example 2: Passing start and end parameters
txt= "Hello I Love AppDividend"
print("Index of love: ",txt.rindex("Love", 3,14))
print("Index of e: ",txt.rindex("e",0,4))
print("Index of AppDividend: ",txt.rindex("AppDividend", 10,25))
print("Index of I: ",txt.rindex("I",7,12))
Output
Index of Love: 8
Index of e: 1
Index of AppDividend: 13
ValueError: substring not found
Ankit Lathiya is a Master of Computer Application by education and Android and Laravel Developer by profession and one of the authors of this blog. He is also expert in JavaScript and Python development.