rfind() searches a string from the right and returns the index of the last place where the substring starts. If the substring is not there, it returns -1 and does not raise an error.
The returned index still counts from the left, so "banana".rfind("an") is 3. Optional start and end limit the search to a slice, and the search is case-sensitive. It is the mirror image of find(), which returns the first match.
text.rfind() is a method of the built-in str type: call it on a string with dot notation. No import is needed, and it never changes the original string.
Syntax
Pass the substring to look for. start and end are optional.
Returns 3. The last l is at index 3, while the first is at index 2.
"report.final.pdf".rfind(".")
Returns 12, the position of the last dot.
"hello".rfind("z")
Returns -1. The substring is not in the string.
Use rindex() when a missing substring should raise ValueError. Use find() for the first match, and rpartition() to split at the last separator in one step.
Library declarations
python
str.rfind(sub[, start[, end]]) -> int
# returns: the highest index where sub starts, or -1 if it is missing
# raises: TypeError if sub is not a string
Parameters
Parameter
Description
sub
Required. The substring to look for. It must be a string, and it can be longer than one character.
start
Optional. Index where the search area begins. Default 0.
end
Optional. Index where the search area stops, exclusive. Default is the end of the string.
Return Value
Return Value
Description
int
The index of the last match, counted from the left, or -1 if there is no match.
Python Examples
Example 1 — Find the Last Occurrence
Compare find() and rfind() on the same text, and try a missing substring.
python
text = "banana"
print(text.find("an"))
print(text.rfind("an"))
print(text.rfind("a"))
print(text.rfind("x"))
Output
1
3
5
-1
How It Works
find() starts at the left. The first "an" begins at index 1.
rfind() starts at the right. The last "an" begins at index 3, so the two methods give different answers.
One letter. The last "a" is the final character, at index 5.
No match."x" is not in the text, so the result is -1.
Example 2 — Separate a Folder From a File Name
Use the last slash and the last dot to cut a path into folder, name, and extension.