Python String rindex() Method – Find Last Occurrence of a Substring

Python String rindex() Method

The rindex() method in Python returns the last index of a substring within a string. It works just like rfind(), but instead of returning -1 when not found, it raises a ValueError.

Syntax

string.rindex(substring, start, end)

Parameters:

  • substring – The string to search for
  • start – (Optional) The starting index to search from
  • end – (Optional) The ending index to search to (not inclusive)

Returns:

  • The highest index where the substring is found.

Raises:

  • ValueError if the substring is not found.

Example 1: Basic Usage

text = "apple banana apple"
print(text.rindex("apple"))
13

Why? The second "apple" starts at index 13, which is the last occurrence.

Example 2: With Start and End Index

text = "one two three two one"
print(text.rindex("two", 0, 15))
4

Why? Within the slice from index 0 to 15, the last "two" appears at index 4.

Example 3: Substring Not Found

text = "hello world"
print(text.rindex("Python"))
ValueError: substring not found

Note: Use rfind() instead if you want to avoid exceptions.

Use Case: Reverse Search

You can use rindex() when you want to find the last occurrence of a word or character in a string — such as locating the last period in a sentence, or the last path in a URL.

Difference Between rfind() and rindex()

MethodReturns if Not Found
rfind()-1
rindex()Raises ValueError

Common Mistakes

  • Using rindex() without checking if the substring exists first
  • Mixing up rfind() and rindex()

Summary

  • rindex() finds the last position of a substring.
  • Raises an error if the substring is not found.
  • Can take optional start and end parameters.

Practice Problem

Write a Python program that reads a sentence and prints the last position of the word "end". If not found, print "Not Found".

sentence = input("Enter a sentence: ")
try:
    print("Last index of 'end':", sentence.rindex("end"))
except ValueError:
    print("Not Found")
Mallikarjuna Mallisetty, author
About the author

Mallikarjuna Mallisetty

General programming

Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.

View LinkedIn profile ↗