×

Struct Module in Python

What is a structure in Python?

An entity that holds data in form of a structure is called a data structure. In Python, the data structure includes tuples, lists, dictionaries, and sets.

To use data structures in Python, we use the struct module. Though this module is available in Python 3.x, and cannot be used in older versions.

Functions in struct module

There are multiple functions available in the struct module that can be easily used after importing this module. The following functions are available in this module

struct.pack()

This function is used to print the string that contains the provided values in the format declared. (The formatting string is a mechanism that is used to specify the format of data while packing and unpacking). To make this mechanism work, the values passed should be passed according to the format, or else an error is raised.

Syntax:

struct.pack(format_string, a1, a2, a3, ....)

Example:

import struct


# Here, format ‘i’ is int in C type
# and the format 'iii' shows 'int intint’.
val=struct.pack('iii',1,2,3)
print(val)
  
# Here, format ‘i’ is int in C type
#and format ‘l’ is long in C type
# and the format 'hhl' shows 'short short long'
val=struct.pack('hhl',1,2,3)
print(val)

Output:

b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00'
b'\x01\x00\x02\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00'

struct.unpack()

This function is used to print the data that is unpacked according to the format specified. It returns the data in the format of a tuple with the size depending on the values passed in the struct.pack() function during packing.

Syntax:

struct.unpack(formatstring, name of string)

Example:

import struct
  
# Here, '?' stands for BOOL, 'h' stands for short, 'i' stands for
#int and 'l' stands for long
val=struct.pack('?hil', True, 3, 8, 668)
print(val)
  
# The struct.unpack() function is used to return tuples
# Variables a1, a2, a3, ... are returned as elements of the tuple
tpl=struct.unpack('?hil', val)
print(tpl)
  
# Here, q stands for long long int and f stands for float
val=struct.pack('qf', 8, 5.3)
print(val)
tpl=struct.unpack('qf', val)
print(tpl)

Output:

b'\x01\x00\x03\x00\x08\x00\x00\x00\x9c\x02\x00\x00\x00\x00\x00\x00'
(True, 3, 8, 668)
b'\x08\x00\x00\x00\x00\x00\x00\x00\x9a\x99\xa9@'
(8, 5.300000190734863)

struct.calcsize()

This function is used to calculate and return the size of the structure corresponding to the given format. This is an important function, as struct.pack() and struct.unpack(), they both require buffer and offset values, and this function is useful for them.

Syntax:

struct.calcsize(format)

Example 1:

import struct
val=struct.pack('?hil', True, 3, 8, 678)
print(val)


# Returning the size of the structure
sze=struct.calcsize('?hil')
print(sze )


sze=struct.calcsize('qf')


print(sze )

Output:

b'\x01\x00\x03\x00\x08\x00\x00\x00\xa6\x02\x00\x00\x00\x00\x00\x00'
16
12

Example 2

import struct
val=struct.pack('bi', 56, 0x12131415)
print(val)


sze=struct.calcsize('bi')
print(sze )


val=struct.pack('ib', 0x12131415, 56)
print(val)


sze=struct.calcsize('ib')
print(sze )

Output:

b'8\x00\x00\x00\x15\x14\x13\x12'
8
b'\x15\x14\x13\x128'
5

Note: The ordering of format characters can have an impact on the size.

Exception struct.error()

The exception struct error tells us the problem with the argument passed; this kind of error is raised when any wrong argument is passed.

Example:

from struct import error
print(error)

Output:

<class 'struct.error'>

Note: This is used only in exception handling, to show the error that occurred.

struct.pack_into()

This function is used to pack the data into the buffer.

Syntax:

struct.pack_into(frmt, bfr, ofst, a1, a2, a3, ...)

Here,

  • frmt: The format for the data type
  • bfr: The writable buffer which starts at offset (optional)
  • a1, a2, a3, ... :The valuesthat are passed

struct.unpack_from()

This function is used to unpack data, and it returns tuples.

Syntax:

struct.unpack_from(frmt, bfr, [ofst = 0])

Here,

  • frmt: The format for the data type
  • bfr: The writable buffer which starts at offset (optional)

Example:

import struct
# To create a string buffer, ctypes are required
import ctypes
  
# Thecalcsize() function is used to calculate the size of the format
siz=struct.calcsize('hhl')
print(siz)
  
# The buffer 'bfr' is created
bfr=ctypes.create_string_buffer(siz)
  
# The struct.pack() function packs the data
# The struct.unpack() function returns the data after unpacking 
a=struct.pack('hhl', 4, 4, 5)
print( a)
b=struct.unpack('hhl', x)
print( b )
  
# The struct.pack_into() function is used topack data into the buffer,
#and it does not return any value
# The struct.unpack_from() function is used to unpack data from the
# thebuffer,and it returns the unpacked values in form of a tuple
struct.pack_into('hhl', bfr, 1, 3, 3, 4)
c=struct.unpack_from('hhl', bfr, 0)
print( c )

Output:

Struct Module in Python

Related Topics

Convert XML to JSON in Python

XML conversion is very useful if we work on an API that returns data in JSON format and the source of data is in XML format. JSON A JSON file reserves the...

4 minutes read.

Python Selectors

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

How to create a dictionary in Python?

How to create a dictionary in python Dictionary is a data structure in Python that represents our data in the form of keys and values. Each value in a dictionary can be...

5 minutes read.

Operator Overloading in Python

In any programming language, + is an arithmetic operator; it adds two numbers to give the sum. Have you ever tried to concatenate two strings? Concatenating two strings is adding...

5 minutes read.

Difference between Expression and Statement in Python

What is an expression in Python? Expression is a combination of operands and operators. Expression helps us to produce some other values. In the python programming language,  expressions produce some other value...

6 minutes read.

Python Parse Text File

We will learn different ways of read text records in Python. TL;DR The accompanying tells the best way to read all texts from the readme.txt document into a string: with open('readme.txt') as f: lines...

5 minutes read.

Python Web Development projects

What is Python? Python is currently one of the most widely used computer programming languages. This isn't just an exaggeration; Python is the second-most famous programming language on the software development...

3 minutes read.

Difference between Python 2 and Python 3

In this tutorial, we will learn the differences between two versions of python, that is, python version 2 and python version 3. Some basic differences include- Python 2 is the older version...

3 minutes read.

Python File Handling

What is the file? The file is a collection of data in a single unit. It is used to store information in the non-volatile memory such as hard-disk. Computer programs generally run on the RAM...

7 minutes read.

Difference between Input() and raw_input() functions in Python

There are two input functions in Python that are used for taking input are given below: raw_input()input() What is raw_input() Function? raw_input() function is a built-in function in Python. It is used to...

6 minutes read.

Python String rindex() method

Python String rindex() method The string. rindex() method in Python returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an...

2 minutes read.

Class and Static Methods in Python

The method is an important concept to learn for every programmer or data analyst. We know that in OOP's concept, each object has its attributes and behaviors defined through methods....

3 minutes read.

CSV Module In Python

Introduction CSV stands for "comma separated values". It is the most common and simple file structure used for storing and arranging tabular data. for example; a spreadsheet or database. It stores...

5 minutes read.

Working with files in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has an...

5 minutes read.

Arguments and parameters in Python

Generally, there is a misunderstanding that parameters and arguments, both are the same. But, as a programmer, you need to understand the difference between these two. Parameters: While defining a function, we...

5 minutes read.

Python String endswith() method

Python String endswith() method The string.endswith() method in Python returns a Boolean value True if the string ends with the specified suffix, otherwise it returns False. Syntax endswith(suffix[, start[, end]]) Parameter suffix – This parameter represents a string or tuple...

2 minutes read.

Python JSON

In this tutorial, we will learn about JSON in the Python programming language. We will focus on its features, Guidelines to be kept in mind while writing its syntax, the...

3 minutes read.

How to slice a list in python

When working with lists, we face situations where we may need a part of the list from one index to the other. Slicing is one of the simpler ways to...

5 minutes read.

Python tuple() function

Python tuple() function The tuple() function in Python creates a tuple object. Syntax tuple([iterable]) Parameter Iterable: This parameter represents a sequence, collection or an iterator object. Return This function returns a tuple object. Example 1 # Python Program explaining #...

1 minute read.

Python Comments

In this tutorial, we will discuss the importance of comments in the Python code and how various types of comments can be inserted in the code. Comments are used to describe...

3 minutes read.