Python String rindex() Method

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

  1. substring(required): It’s the substring that needs to be searched in the given string.
  2. start(optional): Starting position where the substring needs to be checked within the string. (Default is 0)
  3. 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 RepresentationVisual Representation of Python String rindex() Method

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 Visual Representation of Passing start and end parameters to the rindex() method

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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.