Tutorial Study Image

Python rindex()

The rindex() function in python helps to return the highest index means the last occurrence of the given substring from the original string. If the substring is not found the function will raise a ValueError exception. We can also specify the starting and ending positions for the search.

str.rindex(sub[, start[, end]] ) #where start & end are integer values

rindex() Parameters:

The rindex() function takes three parameters. This method is similar to the rfind() method the difference is that, if the substring is not found in the rfind() method it will return -1 as output.

Parameter Description Required / Optional
sub The string to search for Required
start  Where to start the search. Default is 0 Optional
end Where to end the search. Default is to the end of the string Optional

rindex() Return Value

The return value is always an integer. The rindex() method always performs a case-sensitive search.

Input Return Value
If substring Integer(highest index)
If no substring  ValueError exception

Examples of rindex() method in Python

Example 1: How rindex() works in Python?

string = "Hii, How are you."
# substring exist
val = string.rfind("o")
print("Substring1 index:", val)

# substring not exist




Substring index: 14
Traceback (most recent call last):
  File "...", line 8, in 
ValueError: substring not found

Example 2: How rindex() works with start and end in Python?

string = "Python programming language"  
# calling function  
string2 = string.rindex("m",5) # Only starting index is passed  
print("Substring index:", string2)

string2 = string.rindex("o",1,7) # Start and End both indexes are passed  
print("Substring index:", string2)


Substring index: 14
Substring index: 4