Skip to content
Tutorials Center
My learning

Topics

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.

Python
print("a/b/c.txt".rfind("/"))   # 3

Try it

Python Finding the last match

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.

Python Handling -1 correctly

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

Python
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.
  • -1 is a valid-looking index. s[s.rfind(x):] with no match returns the last character. Test for -1 first, or use rindex() style code with try/except if a missing value is a bug.
  • Overlapping matches count. "aaaa".rfind("aa") is 2, the start of the last possible match.
  • Empty substring: "abc".rfind("") returns len(s), here 3.
  • Use in for yes/no. "x" in s is clearer than s.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 bytes and bytearray.