all Python 3structfunction
struct.pack()
packing and unpacking
Packs values into bytes according to a struct format string: numbers, byte strings, flags — in a chosen byte order.
Syntax
data = struct.pack(format, v1, v2, ...)
Without a '<', '>' or '!' prefix the byte order and padding come from the current machine and the result is not portable. A value out of range for its code is struct.error, not silent truncation: 300 does not fit 'B'. The 's' code accepts only bytes, not str, and silently pads with zeros or truncates to the given length.
Examples
import struct
print(struct.pack('>I', 1)) # → b'\x00\x00\x00\x01'
print(struct.pack('<I', 1)) # → b'\x01\x00\x00\x00'
print(struct.pack('<5s', b'abc')) # → b'abc\x00\x00'
import struct
try:
struct.pack('<B', 300)
except struct.error as e:
print(e) # → format requires 0 <= number <= 255
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy