bytes.rpartition(sep) searches for the last occurrence of sep and returns a 3-tuple: the bytes before it, the separator, and the bytes after it.
If the separator is not found, the result is (b'', b'', data): the data goes in the last slot, the mirror image of partition(). It is a natural fit for trailing items such as a port number or a checksum.
bytes.rpartition() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.rpartition(...). No import is needed, and bytearray objects have the same method.
Syntax
Pass the separator and unpack the three parts.
python
before, sep, after = data.rpartition(separator)
Call
What it does
b"a.b.c".rpartition(b".")
Returns (b'a.b', b'.', b'c').
b"abc".rpartition(b".")
Returns (b'', b'', b'abc').
b"x::y".rpartition(b":")
Returns (b'x:', b':', b'y').
When the separator is missing, the data is in the third slot, not the first; handle that case explicitly.
Method signatures
python
bytes.rpartition(sep, /)
# returns a 3-tuple of bytes objects
Parameters
Parameter
Description
sep
The separator to search for (bytes-like, not empty).
Return Value
Return Value
Description
tuple
(before, sep, after) split at the last match, or (b'', b'', data) when not found.
Python Examples
Example 1 — Split Host and Port at the Last Colon
IPv6 addresses contain colons, so splitting at the last one is the right choice. A missing port shows the not-found layout.
python
for addr in [b"example.com:8080", b"[::1]:443", b"localhost"]:
host, _, port = addr.rpartition(b":")
print(host, port)