Home Python Bytes Methods rindex() Python bytes.rindex() Method Definition bytes.rindex() searches from the right and returns the index where the last match starts. When sub is missing it raises ValueError instead of returning -1 like rfind() .
Use it when the final occurrence is required: the dot before an extension that must exist, the last frame delimiter in a capture, or a trailer marker at the end of a message.
bytes.rindex() is a method of the built-in bytes type : call it on a bytes object with dot notation, such as data.rindex(...). No import is needed, and bytearray objects have the same method.
Syntax Same arguments as rfind(), with an exception for missing data.
pos = data.rindex(sub)
pos = data.rindex(sub, start)
pos = data.rindex(sub, start, end) Call What it does b"a.b.c".rindex(b".")Returns 3. b"a.b.c".rindex(b".", 0, 3)Returns 1. b"abc".rindex(b".")Raises ValueError. b"\x00\x01\x00".rindex(0)Returns 2.
Like every search method, the result counts from the left, even though the search starts at the right.
Method signatures bytes.rindex(sub[, start[, end]])
# sub: bytes-like object or int in range(256)
# raises ValueError 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. ValueError Raised when sub does not occur in the searched range.
Python Examples 1. Split an extension 2. Last chunk marker 3. Last flag byte Example 1 — Split a Byte File Name at Its Last Dot A helper splits a name into stem and extension. Names without a dot are rejected with ValueError, which the caller handles.
def split_ext(name):
dot = name.rindex(b".")
return name[:dot], name[dot:]
print(split_ext(b"backup.tar.gz"))
print(split_ext(b"photo.jpeg"))
try:
split_ext(b"README")
except ValueError:
print("no extension in b'README'") (b'backup.tar', b'.gz')
(b'photo', b'.jpeg')
no extension in b'README' How It Works Only the last dot. backup.tar.gz has two dots; rindex() picks the one at 10, so the stem keeps .tar.Tuple of bytes. The helper returns two slices, printed as a tuple of bytes literals.Error travels up. The helper does not catch the exception; the caller decides how to report a name without an extension.Example 2 — Find the Last Chunk Marker in a Stream A stream repeats the marker <A> before every value. The last marker tells you where the newest value starts.
stream = b"<A>1<A>2<A>3"
print(stream.rindex(b"<A>"))
print(stream.rindex(b"<A>", 0, 8))
print(stream[stream.rindex(b"<A>") + 3:]) How It Works Newest marker. The third marker begins at index 8.Earlier window. With end=8 the third marker is out of range, so the second one at 4 is returned.Read the value. Skipping the three marker bytes after the last match leaves b'3'.Example 3 — Locate the Last Flag Byte in a Frame HDLC-style frames use the flag byte 0x7E at both ends. Find the closing flag, then the one before it, and handle a byte that is not present.
frame = b"\x7e\x10\x20\x7e\x30\x7e"
last = frame.rindex(0x7E)
print(last)
print(frame.rindex(0x7E, 0, last))
try:
frame.rindex(0x99)
except ValueError:
print("byte 0x99 not in frame") 5
3
byte 0x99 not in frame How It Works Closing flag. The final 0x7E is at index 5.Search before it. Using last as the end bound finds the previous flag at 3, marking the start of the last frame.Missing value. 0x99 is not in the frame, so rindex() raises ValueError.Frequently Asked Questions What is the difference between rindex() and rfind()? Both return the last match. rfind() returns -1 when nothing is found; rindex() raises ValueError.
What is the difference between rindex() and index()? index() returns the first match from the left; rindex() returns the last match. Both raise ValueError when there is no match.
Can rindex() take an int? Yes. data.rindex(10) returns the position of the last newline byte.
How do I avoid the exception? Check with the in operator first, use rfind() and test for -1, or wrap the call in try/except ValueError.
Does rindex() work on bytearray? Yes. bytearray.rindex() behaves the same way and also accepts any bytes-like needle.
Next: bytes.rjust() Right-justify the bytes in a field, padding on the left with a fill byte.
rjust() → 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.
8 people found this page helpful
Helpful Share Copy link Suggestion