bytes.partition()
Always three parts, whatever the input. That guarantee is the whole point — unpacking can never fail the way it does with split.
Demo
Three parts come back every time. With a separator present you get what is before it, the separator itself, and what is after — and only the FIRST occurrence splits, so "a=b=c" leaves the second equals sign in the tail. When the separator is absent the head holds the entire input and the other two are empty, which is the detail to remember: check the separator, not the tail, to find out whether a split happened.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| sep | bytes | yes | Separator to split on, at its first occurrence. An empty separator raises ValueError. |
Return value
tuple — Always a three-item tuple: (head, separator, tail). When the separator is absent, the head holds everything and the other two are empty.
Common patterns
key, sep, value = line.partition(b'=') if not sep: raise ValueError('missing =')
head, _, body = payload.partition(b'\r\n\r\n')
prefix = data.partition(b'#')[0]
Examples
Pitfalls
b'novalue'.partition(b'=')[2]
h, s, t = data.partition(b'=') if not s: raise ValueError('no separator')
b'a=b=c'.partition(b'=')
b'a=b=c'.split(b'=')
b'abc'.partition(b'')
parts = data.partition(sep) if sep else (data, b'', b'')
b'a=b'.partition('=')
b'a=b'.partition(b'=')
When to use
- Key-value parsing where malformed input must not crash
- Splitting a header from a body at the first delimiter
- Anywhere split(sep, 1) would need a length check afterwards
- You want every field → split
- You want the LAST separator → rpartition
- The data is text → decode first and use str.partition
Notes
FAQ
So that the head always means "everything up to the separator". With no separator, that is the whole input. It also makes data.partition(sep)[0] a safe way to take the prefix whether or not the separator exists.
b'abc'.partition(b'=') # (b'abc', b'', b'')