bytes.split()
The workhorse for chopping up binary records. Note that splitting on a missing separator is not an error — you get a one-item list back.
Demo
Splitting on an explicit separator keeps every field, including empty ones — "a,,b" gives three parts with an empty middle. A separator that is not present is not an error: you get a single-item list holding the whole input, which is what makes unpacking into a fixed number of names fail unpredictably. An empty separator is a ValueError, because it would produce an infinite number of splits.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| sep | bytes | None | no (None) | Separator to split on. Omitted or None splits on runs of ASCII whitespace and drops empty parts. |
| maxsplit | int | no (-1) | Maximum number of splits. The remainder stays in the final element. Negative means no limit. |
Return value
list — A list of bytes objects. Always contains at least one item — the whole input when the separator is absent.
Common patterns
lines = data.split(b'\n')
head, body = data.split(b'\r\n\r\n', 1)
fields = data.split()
Examples
Pitfalls
k, v = b'novalue'.split(b'=')
k, sep, v = b'novalue'.partition(b'=')
b'a,,b'.split(b',')
[p for p in b'a,,b'.split(b',') if p]
b'a,b'.split(',')
b'a,b'.split(b',')
b'abc'.split(b'')
parts = data.split(sep) if sep else [data]
When to use
- Chopping a binary payload into records or lines
- Parsing simple delimited formats read in binary mode
- Splitting off a header with maxsplit
- The data is text → decode first and use str.split
- You want exactly two parts → partition, which never fails to unpack
- Line splitting that must handle CRLF → splitlines
Notes
FAQ
Because there is one field, and it happens to be empty. b''.split(b',') is [b''], not []. The rule is that an explicit separator always produces one more part than there are separators.
b''.split(b',') # [b'']