Python String rindex()
Python String.rindex() method returns the index of last occurrence of specified value in given string. We can also specify the bounds in the strings, in which the search for the given value has to happen, via start and end parameters.
If the value is not present in this string, rindex() returns raises ValueError. In fact, this behavior is the only difference between str.rindex() method and str.rfind() method.
In this tutorial, we will learn the syntax and examples for rindex() method of String class.
Syntax
The syntax of String rindex() method in Python is
str.rindex(value, start, end)
where
Parameter | Required/ Optional | Description |
---|---|---|
value | Required | A string. Index of last occurrence of this value in the string has to be returned. |
start | Optional | An integer. The index from which, the value has to be searched in this string. |
end | Optional | An integer. The index until which, the value has to be searched in this string. |
Examples
rindex() with Default Parameter Values
In the following program, we take a string 'abcd-abcd-abcd'
in x
, and find the index of the value 'bc'
in the string x
.
Example.py
x = 'abcd-abcd-abcd'
value = 'cd'
result = x.rindex(value)
print("Index :", result)
Output
Index : 12
Explanation
'a b c d - a b c d - a b c d'
0 1 2 3 4 5 6 7 8 9 10 11 12 13
c d : index of 'cd' is 12
The index of last occurrence of value 'cd'
is 12.
Even though there are multiple occurrences of the given value 'cd'
in this string, rindex() method returns only the index of last occurrence.
rindex() with Value not in String
We already know that rindex() raises a ValueError if the specified value is not present in the string.
Example.py
x = 'abcd-abcd-abcd'
value = 'xy'
result = x.rindex(value)
print("Index :", result)
Output
Traceback (most recent call last):
File "/Users/tutorialkart/PythonTutorial/Example.py", line 3, in <module>
result = x.rindex(value)
ValueError: substring not found
rindex() with Specific Start
In the following program, we will specify a starting position/index from which the search for the value value in the string has to happen.
Example.py
x = 'abcd-abcd-abcd'
value = 'cd'
start = 5
result = x.rindex(value, start)
print("Index :", result)
Output
Index : 12
Explanation
'a b c d - a b c d - a b c d'
0 1 2 3 4 5 6 7 8 9 10 11 12 13
|
start=5 from this position
c d : index of 'cd' is 12
rindex() with Specific Start and End
In the following program, we will specify the bounds [start, end] for index, for searching the given value in the string.
Example.py
x = 'abcd-abcd-abcd'
value = 'cd'
start = 5
end = 9
result = x.rindex(value, start, end)
print("Index :", result)
Output
Index : 7
Conclusion
In this Python Tutorial, we learned how to find the index of last occurrence of specified value in given string, using String method – rindex().