This guide explains str.rfind Method: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
str.rfind(substring, start, end) searches from the right and returns the highest index where the substring occurs, or -1 when absent. It is useful when the last occurrence matters.
When You Would Use This
Find the final separator in a file-like label.
Step-by-Step Example
label_text = "report.archive.csv"
last_dot_position = label_text.rfind(".")
print(last_dot_position)
print(label_text[last_dot_position + 1:])
How the Example Works
The last dot position points to the separator before csv. The slice retrieves csv; check for -1 in code where the separator may be absent.
Example Output
14
csv
Try It Yourself
Extract the final segment of "one/two/three" using rfind().
Common Beginner Mistakes
- Assuming the index is measured backward from zero.
- Treating
-1as a valid positive match. - Confusing
rfind()with a reverse-string search that changes the input.
Key Takeaways
str.rfind(substring, start, end)searches from the right and returns the highest index where the substring occurs, or-1when absent.- The last dot position points to the separator before
csv. - Avoid this mistake: Assuming the index is measured backward from zero.