Python string rindex() method
Python String rindex() Method
Description
The rindex() method returns the index of the last occurrence of the substring sub or raises a ValueError exception if the index is not found. The search can optionally be restricted to string[beg:end]
.
Syntax
The syntax of the rindex() method is as follows:
var.rindex(sub, beg=0, end=len(string))
Parameters
- sub – Specifies the string to search for.
- beg – The starting index, which defaults to 0.
- end – Ending index. If the optional max parameter is given, only the first count occurrences are replaced.
Return Value
This method returns the last index if found; otherwise, if str is not found, an exception is raised.
Example
The following example demonstrates the use of the rindex() method.
var = "Explicit is better than implicit."
var1 = var.rindex('i')
print("original string:", var)
print("index of 'i':", var1)
var2 = var.rindex('x', 10, -1)
print("index of 'x':", var2)
Running this program will produce the following output −
original string: Explicit is better than implicit.
index of 'i': 30
Traceback (most recent call last):
File "C:Usersmlathexamplesmain.py", line 7, in <module>
var2 = var.rindex('x', 10, -1) ^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: substring not found
Because the letter x does not exist in the string after the 10th index, the program raises a ValueError exception.