Yandex

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")


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M