×

Python Struct

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. The python language can also be used in web development; Django and Flask are the frameworks used to create web applications using Python. In Python, indentation is the main concept; if we do not follow proper indentation, the code may not run. We can easily create an application in Python if we are familiar with indentation, Variables, Operators, loop concepts and function concepts in python language. The python programming language has pre-installed modules, which help perform various operations, and one of the modules is the struct module.

Struct Module in Python

The struct module is available in the python programming language; this module helps convert the Python values and the C structs; these Cstructs are represented as the python bytes objects.

This module helps handle the binary data stored in the files. The Format strings are the mechanism used to specify the expected layout when packing and unpacking the data. The struct module is available in Python 3. x, so for running the code, we need to use the Python3 interpreter, and it is not available in Python 2. x so that we can run the code in other interpreters rather than Python 3.

Struct Functions

There are many built-in functions available in the struct module. The struct function takes the buffer argument, the objects in the module use the buffer protocol, and in return, it will provide us with the readable or read-writeable buffer. The most commonly used types for this buffer protocol are the bytes and bytearray. Other types are viewed as the array of bytes that will implement the buffer protocol so that this data can be read without additional copying from the bytes object.

 Now let us look at some of the built-in functions available in the struct module:

1. struct.pack( ):

This method or function will return the string containing the values a1,a2,a3,a4…. these values are packed according to the given format; the Format strings is a mechanism used to specify the expected layout when the packing and the unpacking of the data are done. We need to follow the format used by the Format strings; otherwise, it will raise the struct.error

Syntax:

Struct.pack( format,   a1, a2, a3 ,……)

Parameters:

  • Format: This is the format used to format the given data into the required format.
  • a1, a2, a3…: These are the values provided to the function that must be formatted.

Code:

# importing the library
importstruct
# Format: d is short in C type
# Format: a is int in C type
#Format: ‘daa', which stands for 'short intint.'


data = struct.pack(‘daa’, 1, 2, 3)
print( data )


# Format: j is long in C type
# Format: ‘jjj’ stands for ‘ longlonglong ‘


data  =struct.pack(‘jjj’, 1,2,3)
print(data)

Output:

b’\x01\x00\x02\x00\x00\x01\x02\x02\x00\x01\x00\x00\x01\x02\x00\x01\x01\x00’
b’\x01\x00\x01\x00\x02\x00\x01\x02\x01\x02\x01\x03\x01\x01\x01\x00\x01\x01’

2. Struct.unpack( ):

This method or function will return the unpacked values a1, a2, a3, a4…. these values are packed according to the format; the Format strings are a mechanism used to specify the expected layout when the packing and the unpacking of the data are done. These values are returned as a tuple whose size equals the total number of values passed to the struct.pack( ) during the packing.

Syntax:

Struct.unpack(format,  string)

Parameters:

  • Format: This is the format used to format the given data into the required format.
  • String: This string will contain unpacked values using the unpack( ) function.

Code:

# importing the library
importstruct
# Format: d is short in C type
# Format: a is int in C type
#Format: ‘daa', which stands for 'short intint.'


data = struct.pack(‘daa’, True, 1, 2, 3)
print( data )


# Using the struct.unpack( ) function
# The variables a1,a2,a3,….  these values are returned as the elements in the tuple
struct.unpack(‘data, data)
tup)

Output:

b’\x01\x00\x02\x00\x00\x01\x02\x02\x00\x01\x00\x00\x01\x02\x00\x01\x01\x00’
(True, 1, 2, 3)
b’\x01\x00\x02\x00\x00\x01\x02\x02\x00\x01’
(1, 3.6567)

Here the ‘b’ stands for the binary output. We can observe that the output is returned the values in the form of a tuple as we used the unpack( ) function.


Related Topics

Google Chrome API in Python

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....

3 minutes read.

Create First GUI Application using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 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.

Returning Multiple Values in Python

Python is considered a general-purpose programming language; it is a high-level programming language that is not much difficult and easier to learn. It is rich in libraries that can be...

3 minutes read.

Python program to print array element present at even position

Python program to print array element present at even position In this program, we'll see a Python program that prints the elements of an array that are in even positions. We...

1 minute read.

Python Slice from Last Occurrence of K

Introduction We already know that in Python, cutting produces a sub-string out of a string. The variables start, stop, and step are used to set the slicing range. When dealing on...

3 minutes read.

After Python, What Should I Learn

Python is a programming language used to create websites, software, and other projects. It is easy to code and easy to learn. After learning Python, there are many different directions...

4 minutes read.

How to get current date in python?

How to get current date in python? In Python programming language, date and time are not just a data form, but it is possible to import a method called datetime to operate...

3 minutes read.

Program of Cumulative Sum in Python

Introduction This tutorial, explains what is meant by lists, the cumulative total, several approaches to calculating the cumulative sum of digits in a list, etc. Learn the straightforward Python codes for...

5 minutes read.

Python Operator Precedence

Before knowing about the operator precedence in Python, we have to know about the operators in Python. So let's have a look at it. According to one definition, the operator is...

3 minutes read.

Python Dictionary

Dictionary in Python is an unordered collection of data values, which is used to store data values like a map. Unlike different data types that hold just individual assets as...

4 minutes read.

How to Call a Function in Python

How To Call a Function in Python Functions are the well-defined and structured piece of code that is used to implement specific functionality. Calling a function in python is the best...

4 minutes read.

Python List reverse() method

 Python List reverse() method The list.reverse () method in Python reverses the elements of the list in place. Syntax list.reverse() Parameter NA Example 1 # Python program explaining # the list.reverse() method weekList = ['Sun','Thurs','Mon','Fri', 'Tues', 'Wed'] print("Actual week list: ",weekList) #...

1 minute read.

Abstraction in Python

What is meant by abstraction generally? A very general notion of a thing or work is known as abstract. To be more precise, the process of having a brief idea but...

4 minutes read.

Convert List to Array in Python

What is List in Python? In Python, a list is a built-in data structure that stores a collection of items. The items in a list can be of any data type,...

3 minutes read.

Subprocess in Python

In this tutorial, we will understand what is a subprocess in python and will understand how to use it. Subprocess A subprocess is a very prevailing portion of the python library. It...

3 minutes read.

Cube Root in Python

In general, the cube is a three-dimensional solid figure that has 6 square faces. It is also called a geometrical shape with six equal faces, eight vertices, and twelve edges....

3 minutes read.

Face Recognition in Python

In this tutorial, we will understand what is face recognition and how it is achieved in python. Face recognition is of great utility in real-world scenarios. It is an extended step...

3 minutes read.

Python String Lowercase

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....

3 minutes read.

Python email utils

Python is a popular programming language in this growing world. There are many resources to learn python online without spending a single penny. In this article, we will talk about a...

4 minutes read.