str.rfind()
Locate a substring's LAST occurrence: highest index, or -1 when absent. The right-scanning mirror of str.find.
Demo
rfind scans from the RIGHT: it returns the HIGHEST index where sub appears in the substring s[start:end], or -1 when there is no occurrence. The start / end bounds are applied first, then the search runs backward. An empty sub is found at every position — rfind returns end (or len when end is default).
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| sub | str | yes | The substring to locate. |
| start | int | no (0) | Slice start, supports negative indexing. The search is bounded to s[start:end]. |
| end | int | no (len(s)) | Slice end (exclusive), supports negative indexing. |
Return value
int — The highest index where sub is found, or -1 when it does not occur. Never raises for a missing substring — the non-raising sibling of str.rindex.
Common patterns
i = name.rfind(".") ext = name[i+1:] if i != -1 else ""
i = url.rfind("/") tail = url[i+1:] if i != -1 else url
i = s.rfind(sub, 0, cutoff) # search only in s[:cutoff]
Examples
Pitfalls
if line.rfind("ERROR"): log_error() # runs on -1 too
if line.rfind("ERROR") != -1: log_error()
"hello".rindex("z")
"hello".rfind("z")
"hello world".rfind("o", 8, 11)
"hello world".rfind("o", 0, 11)
"hello".rfind("")
if sub and s.rfind(sub) != -1: ...
When to use
- Splitting a filename at the last dot
- Extracting the tail after the last delimiter
- Finding the last occurrence of any substring in a search-and-replace tool
- When "not found" should be handled silently, not with an exception
- You want an exception on missing → str.rindex
- You need the first occurrence → str.find
- You need to know how many matches → str.count
- You need every match position → a loop with find or re.finditer
Notes
FAQ
rfind returns -1 on a missing substring; rindex raises ValueError. Same pair as find/index. Pick rfind when absence is expected and cheap; pick rindex when absence is a hard error you want to trip.