sep.join(iterable) returns a new bytes object made by concatenating every item of iterable, with sep inserted between neighbors. The separator is the object you call the method on, for example b",".join(fields).
Every item must be a bytes-like object: bytes, bytearray, or memoryview. Using b"".join(parts) is the efficient way to assemble many pieces, much faster than repeated + in a loop.
bytes.join() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.join(...). No import is needed, and bytearray objects have the same method.
Syntax
Call it on the separator and pass the pieces.
python
result = sep.join(iterable)
result = b"".join(parts)
Call
What it does
b",".join([b"a", b"b"])
Returns b'a,b'.
b"".join([b"\x01", b"\x02"])
Returns b'\x01\x02'.
b"-".join([])
Returns b''.
The separator only goes between items, never before the first or after the last.
Method signatures
python
bytes.join(iterable, /)
# iterable: items must be bytes-like objects
Parameters
Parameter
Description
iterable
Any iterable (list, tuple, generator) whose items are bytes-like objects.
Return Value
Return Value
Description
bytes
The items concatenated with the separator between them (bytearray when the separator is a bytearray).
Python Examples
Example 1 — Build a CSV Row and CRLF Protocol Lines
Join fields with commas, protocol lines with CRLF, and raw bytes with no separator at all.
Terminate the last line.join() adds CRLF only between lines, so the final one is appended separately.
Empty separator.b"" simply concatenates the pieces.
Example 2 — Every Item Must Be bytes-like
A str item breaks the join. Encode numbers first, and see that bytearray and memoryview items are fine.
python
parts = [b"a", "b", b"c"]
try:
b"-".join(parts)
except TypeError:
print("every item must be bytes-like")
numbers = [1, 2, 3]
print(b"-".join(str(n).encode("ascii") for n in numbers))
print(b"".join([bytearray(b"x"), memoryview(b"y")]))
Output
every item must be bytes-like
b'1-2-3'
b'xy'
How It Works
One bad item. The str "b" in the middle raises TypeError.
Encode numbers. A generator converts each int to its ASCII digits before joining.
Mixed bytes-like items. bytearray and memoryview items are accepted, and the result is bytes because the separator is bytes.
Example 3 — Assemble a Binary Packet
A packet has a two-byte sync header, a one-byte length, and the payload. Join the pieces, then inspect the result.