Python Reference ยท String Methods
Python str.rfind() method
Reference for Python str.rfind(): find the highest index of a substring, return -1 when missing, use start and end bounds, and compare with find() and rindex().
The str.rfind() method returns the highest index at which a substring is found, searching from the right end of the string. If the substring does not occur, it returns -1 instead of raising an error.
It is the mirror image of find(). Reach for it when the last occurrence matters, such as the final dot in a file name or the last slash in a path.
print("a/b/c.txt".rfind("/")) # 3
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
str.rfind(sub) str.rfind(sub, start) str.rfind(sub, start, end)
| Name | Description |
|---|---|
sub |
The substring to look for. |
start |
Optional. Index at which the searched range begins. |
end |
Optional. Index at which the searched range stops (exclusive). |
Return value: the highest index (counted from the left, as usual) at which sub starts within s[start:end], or -1.
Raises: TypeError if sub is not a string.
Usage notes
- The index is from the left.
rfind()only searches from the right; the number it returns is still a normal index, not a negative offset. -1is a valid-looking index.s[s.rfind(x):]with no match returns the last character. Test for-1first, or userindex()style code withtry/exceptif a missing value is a bug.- Overlapping matches count.
"aaaa".rfind("aa")is2, the start of the last possible match. - Empty substring:
"abc".rfind("")returnslen(s), here3. - Use
infor yes/no."x" in sis clearer thans.rfind("x") != -1. - Bounds are slice-like and negative values count from the end. The returned index is relative to the whole string.
- Splitting at the last separator is usually neater with
rpartition(), which needs no index math. - Also on
bytesandbytearray.