Content · Programming · Python

Python str.rindex Method: Usage and Examples

str.rindex(substring, start, end) finds the last occurrence of a substring, like rfind(), but raises ValueError when it cannot find one. Learn with a clear example and common mistakes to avoid.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

This guide explains str.rindex Method: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.

Understanding the Concept


str.rindex(substring, start, end) finds the last occurrence of a substring, like rfind(), but raises ValueError when it cannot find one.

When You Would Use This


Read the final segment of a required dotted identifier.

Step-by-Step Example


qualified_name = "app.settings.region"
last_separator = qualified_name.rindex(".")
print(qualified_name[last_separator + 1:])

How the Example Works


The output is region. This method suits input that is guaranteed to have a dot; use a check or exception handler for optional delimiters.

Example Output


region

Try It Yourself


Catch ValueError and display a friendly message for identifiers without a dot.

Common Beginner Mistakes


  • Expecting -1 when the substring is absent.
  • Confusing the highest matching index with a negative index.
  • Allowing ValueError to crash user-facing code when the input is not guaranteed.

Key Takeaways


  • str.rindex(substring, start, end) finds the last occurrence of a substring, like rfind(), but raises ValueError when it cannot find one.
  • The output is region.
  • Avoid this mistake: Expecting -1 when the substring is absent.
Share this resourceSend this page to someone who may find it useful.