Python Glossary Русский

all Python 3structfunction

struct.unpack()

packing and unpacking

Unpacks bytes according to a struct format and returns a tuple of values.

Syntax

values = struct.unpack(format, buffer)

The result is always a tuple, even for one field: n = unpack('<I', b) gives (1,), not 1, so write n, = ... or index [0]. The buffer length must equal calcsize(format) exactly — to read the start of a longer buffer use unpack_from. Byte order and signedness come from the format: the same two bytes read as '>h' and '<H' are entirely different numbers.

Examples

import struct
n, = struct.unpack('<I', b'\x01\x00\x00\x00')
print(n)  # → 1
print(struct.unpack('>h', b'\xff\xfe'))  # → (-2,)
print(struct.unpack('<H', b'\xff\xfe'))  # → (65279,)
import struct
try:
    struct.unpack('<I', b'abcdef')
except struct.error as e:
    print(e)  # → unpack requires a buffer of 4 bytes

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy