liveBook · Manning

Struct.pack

As explained in The Quick Python Book, Fourth Edition

struct.pack is a struct-module function that converts supplied Python values into a packed byte sequence according to a format string.

struct.pack converts supplied Python values into a packed byte sequence. Pass a format string first, followed by enough values to satisfy its format codes. section 13.7

Format strings describe the binary record:

  • Use codes such as h for a C short integer, d for a double-precision float, and s for a string. section 13.7
  • Prefix a code with a count to specify multiple values or a fixed-size string; 7s represents seven characters. section 13.7
  • Combine codes for a record, such as hd7s, then use struct.calcsize to determine how many bytes each record occupies. section 13.7

Pack one binary record

record_format = 'hd7s' data_record = struct.pack(record_format, 42, 3.14, b'goodbye') The result is a file-ready byte sequence containing the integer, floating-point value, and seven-character string.

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines format codes and argument matching, then connects packing with size calculation and unpacking without detailing every code.
Examples
Packs 42, 3.14, and b'goodbye' with 'hd7s' into a binary record.
What you can do after
Build it from scratch by packing values into a binary record and writing the resulting bytes.
How it connects
Connects format strings with struct.calcsize, struct.unpack, binary files, and endianness options.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.