Home Python Bytes Methods rfind() Python bytes.rfind() Method Definition bytes.rfind() works like find() but searches from the right : it returns the index where the last match starts, or -1 when there is no match.
It is the natural tool for anything defined by its final separator: the last / in a byte path, the last dot before a file extension, or the last newline in a buffer that may end with a half-received record.
bytes.rfind() is a method of the built-in bytes type : call it on a bytes object with dot notation, such as data.rfind(...). No import is needed, and bytearray objects have the same method.
Syntax Same arguments as find(); only the search direction changes.
pos = data.rfind(sub)
pos = data.rfind(sub, start)
pos = data.rfind(sub, start, end) Call What it does b"a/b/c".rfind(b"/")Returns 3. b"a/b/c".rfind(b"/", 0, 3)Returns 1: only b"a/b" is searched. b"abc".rfind(b"z")Returns -1. b"abc".rfind(b"")Returns 3: the empty needle matches at the very end.
The index is counted from the left, like every Python index; only the search starts at the right.
Method signatures bytes.rfind(sub[, start[, end]])
# sub: bytes-like object or int in range(256)
# returns -1 when sub is not found Parameters Parameter Description sub The bytes to look for, or one byte value as an int 0-255. start Optional. Lowest index the match may start at. end Optional. The match must end before this index.
Return Value Return Value Description int The highest index where sub starts. -1 Returned when sub does not occur in data[start:end].
Python Examples 1. Split a byte path 2. Keep partial records 3. Search a byte value Example 1 — Split a Byte Path at the Last Slash File system APIs can return paths as bytes. rfind() finds the final separator, which divides the directory from the file name.
path = b"/srv/app.v2/logs/error.log"
cut = path.rfind(b"/")
print(cut)
print(path[:cut], path[cut + 1:])
print(path.rfind(b"."), path.find(b".")) 16
b'/srv/app.v2/logs' b'error.log'
22 8 How It Works Last separator. Four slashes exist, and the one before error.log sits at index 16.Two slices. Everything before the cut is the directory; everything after it is the file name.Direction matters for dots. rfind(b".") finds the extension dot at 22, while find(b".") stops at the dot inside the directory name app.v2.Example 2 — Separate Complete Records from a Partial One Data from a socket arrives in pieces, so the last record may be cut off. Everything up to the last newline is complete; the rest must wait for more data.
buffer = b"temp=21\ntemp=22\ntemp=2"
end = buffer.rfind(b"\n")
complete, leftover = buffer[:end], buffer[end + 1:]
print(end)
print(complete.split(b"\n"))
print(leftover) 15
[b'temp=21', b'temp=22']
b'temp=2' How It Works Last full line. The second newline, at index 15, is the last one in the buffer.Process what is safe. split() breaks the complete part into two readings.Keep the tail. b'temp=2' is an unfinished reading; a real program would prepend it to the next chunk received.Example 3 — Search Backwards for a Byte Value Here 0xAA marks the start of each record. Search for it as an int, limit the range, and look for a two-byte pattern.
data = b"\xaa\x01\xaa\x02\xaa\x03"
print(data.rfind(0xAA))
print(data.rfind(0xAA, 0, 4))
print(data.rfind(b"\xaa\x02"))
print(data.rfind(b"\xbb")) How It Works Newest record. The last 0xAA marker is at index 4.Bounded search. With end=4 only indexes 0 to 3 count, so the last marker there is at 2.Pattern search. The marker followed by record number 2 appears once, starting at 2.Absent byte. 0xBB never occurs, so the result is -1.Frequently Asked Questions What is the difference between rfind() and find()? find() returns the first match from the left and rfind() returns the last one. Both return -1 when there is no match.
Does rfind() return a negative index for the match? No. The result is a normal index counted from the left. Only -1 is special, and it means not found.
How do I get a file extension from a bytes path? Use dot = name.rfind(b"."), check that it is not -1, and slice name[dot:]. os.path.splitext() also accepts bytes paths.
What should I use if a missing separator is an error? Use rindex(). It returns the same index as rfind() but raises ValueError instead of returning -1.
Can rfind() look for an int? Yes. An int from 0 to 255 is treated as a single byte, for example data.rfind(10) finds the last newline.
Next: bytes.rindex() Like rfind(), but raise ValueError when the byte sequence is not found.
rindex() → About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
7 people found this page helpful
Helpful Share Copy link Suggestion