×

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

Application to Search Installed Application using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python Sys Stdout

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Check if the directory exists in Python

To prevent any error, while loading or editing a file, we first have to check that the directory or the file exists or not. This is also done to prevent...

5 minutes read.

Python logging Module

Python logging Module Introduction By logging word we understand the tracking of the events which happens when we run some software. Logging process is very important part for developing software, debugging...

12 minutes read.

Python Variables

Variables are one of the most important terms we should be familiar with if we want to be good programmers. In simpler words, we use variables to store a value....

4 minutes read.

Python Encapsulation

What is meant by Encapsulation? The process of restricting access to the methods and variables so that accidental modification of data can be prevented is known as Encapsulation. The motive of Encapsulation:...

3 minutes read.

Python String expandtabs() method

Python String expandtabs() method The string.expandtabs() method in Python returns a copy of the string where all tab characters are expanded using spaces. Syntax String.expandtabs([tabsize]) Parameter tabsize: This parameter specifies the number of characters to...

1 minute read.

Python List clear() method

Python List clear() method The list.clear () method in Python extends the list by appending all the items from the iterable. Syntax list.clear() Parameter NA Example 1 # Python Program explaining # the list.clear() method week_list = ["Monday", "Tuesday", "Wednesday","Thursday","Friday",...

1 minute read.

Python while loop

Loops are essential in Python or any other programming language, as they help to execute a block of code repetitively. Sometimes, situations arise where you would need to use a piece of code...

2 minutes read.

List in Python

What is List in Python In Python, lists are used to store the multiple values in one variable. We can say that list is the collection of similar as well as...

3 minutes read.

How to Convert String to List In Python?

How to Convert String to List In Python? We all are familiar with what strings and lists are, let us have a quick revision on them- Strings are a sequence of characters...

4 minutes read.

Continue and Pass Statements in Python

Difference between continue and pass statements in Python The tasks can be repeated and automated efficiently using loops in Python. Sometimes we have to exit from the entire loop completely, we...

2 minutes read.

Yield Statement In Python

The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.  The yield statement hauls the function and returns back the...

2 minutes read.

How to open a file in python

Opening a File in Python Python is a user-friendly programming language that makes almost every concept easy. It provides many inbuilt functions in its libraries to work with files. Using these...

6 minutes read.

Python IDE

What is an IDE?  An IDE or an Integrated Development Environment is a type of software where developers can develop many software’s and applications and run the programs inside it. An...

11 minutes read.

GET and POST requests using Python

‘GET’ and ‘POST’ are two request methods of Hypertext Transfer Protocol (HTTP). What is HTTP? HTTP stands for Hypertext Transfer Protocol. It is a collection of protocols which makes communication between client...

4 minutes read.

How to comment multiple lines in python?

How to comment multiple lines in python There are two qualities that come up with every good and successful programmer- i) Indenting the code ii) Using comments in the code Let us see how...

4 minutes read.

Parameter Passing in Python

In Python, when we characterize capabilities with default values for specific boundaries, it is said to have its contentions set as a possibility for the client. Clients can either pass their...

3 minutes read.

Python Call Function

In this article, you will learn about calling a function in Python. But before learning this, we should know about functions in Python.So, let’s get some overview of functions in...

6 minutes read.

Anytree Python

Python's anytree module is frequently used within data science-related software. Anytree has a Tolerant License, a Construct File that is public, no errors, no risks, and excellent support. One may...

3 minutes read.