str.rfind()
str.rfind(sub[, start[, end]]) int · Added in v3.x · Updated March 13, 2026 · String Methods The .rfind() method searches for a substring within a string and returns the highest index where the substring is found. The “r” stands for “right” — it searches from the end of the string toward the beginning. If the substring is not found, it returns -1 instead of raising an exception.
This makes .rfind() useful when you need to locate the last occurrence of something, like the final slash in a path or the last instance of a word you want to replace.
Syntax
str.rfind(sub[, start[, end]])
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| sub | str | — | The substring to search for |
| start | int | 0 | Beginning index to search from |
| end | int | len(str) | Ending index to search up to |
Return Value
Returns an integer representing the highest index where the substring is found. Returns -1 if the substring is not present in the string.
Examples
Basic search
text = "Hello, world"
print(text.rfind("l"))
# 10
print(text.rfind("z"))
# -1
Finding the last occurrence
path = "/home/user/documents/file.txt"
last_slash = path.rfind("/")
print(last_slash)
# 20
filename = path[last_slash + 1:]
print(filename)
# file.txt
Using start parameter
text = "apple banana apple cherry apple"
print(text.rfind("apple"))
# 26
# Search only in the first half of the string
print(text.rfind("apple", 0, 20))
# 13
Using start and end
text = "ababa"
print(text.rfind("aba"))
# 2
print(text.rfind("aba", 1))
# 2
Common Patterns
Check if substring exists
text = "Python is great"
if text.rfind("is") != -1:
print("Found!")
Find the last extension in a filename
filename = "archive.tar.gz"
last_dot = filename.rfind(".")
if last_dot != -1:
extension = filename[last_dot:]
print(extension)
# .gz
Replace the last occurrence
def replace_last(text, old, new):
idx = text.rfind(old)
if idx == -1:
return text
return text[:idx] + new + text[idx + len(old):]
result = replace_last("foo bar foo", "foo", "baz")
print(result)
# foo bar baz
Parse a URL’s last segment
url = "https://api.example.com/v1/users/123/profile"
last_slash = url.rfind("/")
resource_id = url[last_slash + 1:]
print(resource_id)
# profile
Edge Cases
Empty substring
text = "hello"
print(text.rfind(""))
# 5
Finding an empty string returns the length of the string because "" exists at every position, and rfind returns the highest such position.
Substring appears once
text = "hello"
print(text.rfind("o"))
# 4
print(text.rfind("e"))
# 1
When the substring appears only once, rfind and find return the same index.
Overlapping matches
text = "aaa"
print(text.rfind("aa"))
# 1
print(text.find("aa"))
# 13
With overlapping matches, rfind returns the rightmost starting position (1), while find returns the leftmost (0).