bytes.partition(sep) searches for the first occurrence of sep and returns a 3-tuple: the bytes before it, the separator itself, and the bytes after it.
If the separator is not found, the result is (data, b'', b''). Because the tuple always has three items, you can unpack it safely without checking first, which makes it ideal for name: value header lines.
bytes.partition() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.partition(...). 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.partition(separator)
Call
What it does
b"k=v".partition(b"=")
Returns (b'k', b'=', b'v').
b"k=v=w".partition(b"=")
Returns (b'k', b'=', b'v=w').
b"kv".partition(b"=")
Returns (b'kv', b'', b'').
Check whether the separator was found by testing the middle item: it is empty only when nothing matched.
Method signatures
python
bytes.partition(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) when found, or (data, b'', b'') when not found.
Python Examples
Example 1 — Parse an HTTP Header Line
Separate a header name from its value, then pull a parameter out of the value with a second partition.