bytes.rindex()
rfind with the raising failure mode. Use it when the separator is required and its absence means the input is malformed.
Demo
Same reverse scan as rfind, same left-counted offset — abcabc gives 4 for b, the last occurrence. The difference is the failure case: a missing sequence raises ValueError rather than returning -1. Choose rindex when the thing you are looking for must be there, so that its absence stops the program instead of producing a plausible -1.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| sub | bytes | int | yes | Byte sequence to locate. An int from 0 to 255 searches for that single byte. |
| start | int | no (0) | Left boundary of the searched region. |
| end | int | no (len) | Right boundary, exclusive. |
Return value
int — Byte offset of the last occurrence. Raises ValueError with the message "subsection not found" when absent.
Common patterns
i = path.rindex(b'/') directory, leaf = path[:i], path[i + 1:]
try: i = ref.rindex(b':') except ValueError: raise ValueError('expected host:port')
head, sep, tail = ref.rpartition(b':')
Examples
Pitfalls
b'abc'.rindex(b'z')
i = b'abc'.rfind(b'z') if i == -1: ...
b'abcabc'.rindex(b'b')
len(d) - d.rindex(b'b') - 1
try: b'abc'.rindex('z') except ValueError: ...
b'abc'.rindex('z'.encode())
When to use
- A required trailing separator whose absence is an error
- Parsing where a missing marker means malformed input
- Absence is normal → rfind
- Splitting on the separator → rpartition
- The FIRST occurrence → index
Notes
FAQ
rindex when a missing value is a bug — you get a ValueError at once. rfind when absence is ordinary — you get -1 and decide what to do. If you would write "if i == -1: raise" anyway, rindex already does it.