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
-1when the substring is absent. - Confusing the highest matching index with a negative index.
- Allowing
ValueErrorto crash user-facing code when the input is not guaranteed.
Key Takeaways
str.rindex(substring, start, end)finds the last occurrence of a substring, likerfind(), but raisesValueErrorwhen it cannot find one.- The output is
region. - Avoid this mistake: Expecting
-1when the substring is absent.