struct module in Python

The struct module in Python converts native Python data types into strings of bytes and vice versa. It's a built-in module that uses C-style format characters to specify data types and their binary representation.

Format Characters

The struct module uses format characters similar to C language data types ?

Data Type Format Character Description
int i 4-byte signed integer
char c 1-byte character
string s char[] (requires length prefix)
float f 4-byte floating point

struct.pack() - Converting to Bytes

The struct.pack() method converts Python data types into bytes. The first argument is a format string specifying data types, followed by the values to pack ?

import struct

# Pack a 14-character string and an integer
result1 = struct.pack('14s i', b'Tutorialspoint', 2020)
print(result1)

# Pack two integers, a float, and a 3-character string
result2 = struct.pack('i i f 3s', 1, 2, 3.5, b'abc')
print(result2)
b'Tutorialspoint\x00\x00\xe4\x07\x00\x00'
b'\x01\x00\x00\x00\x02\x00\x00\x00\x00\x00`@abc'

struct.unpack() - Converting from Bytes

The struct.unpack() method converts bytes back to Python data types. It takes the format string and the packed bytes, returning a tuple of values ?

import struct

# Pack data first
packed_data = struct.pack('14s i', b'Tutorialspoint', 2020)
print("Packed:", packed_data)

# Unpack the bytes back to original data types
unpacked_data = struct.unpack('14s i', packed_data)
print("Unpacked:", unpacked_data)
print("String:", unpacked_data[0].rstrip(b'\x00'))  # Remove null bytes
print("Integer:", unpacked_data[1])
Packed: b'Tutorialspoint\x00\x00\xe4\x07\x00\x00'
Unpacked: (b'Tutorialspoint\x00\x00', 2020)
String: b'Tutorialspoint'
Integer: 2020

Practical Example

Here's a practical example showing how to pack and unpack mixed data types ?

import struct

# Pack user data: ID (int), name (10 chars), score (float)
user_id = 12345
name = b'Alice'
score = 95.7

# Pack the data
packed = struct.pack('i 10s f', user_id, name, score)
print(f"Packed data: {packed}")
print(f"Size: {len(packed)} bytes")

# Unpack the data
unpacked_id, unpacked_name, unpacked_score = struct.unpack('i 10s f', packed)
print(f"ID: {unpacked_id}")
print(f"Name: {unpacked_name.rstrip(b'\x00').decode()}")  # Remove padding and decode
print(f"Score: {unpacked_score}")
Packed data: b'90\x00\x00Alice\x00\x00\x00\x00\x00ffffff_@'
Size: 18 bytes
ID: 12345
Name: Alice
Score: 95.69999694824219

Conclusion

The struct module is essential for binary data manipulation and interfacing with C libraries. Use pack() to convert Python data to bytes and unpack() to convert bytes back to Python data types.

Updated on: 2026-03-25T09:04:41+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements