×

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

Word frequency Python

Word frequency Python In this tutorial, we will write the Python program to count the occurrence of a word (word frequency) in a given sentence. We will learn all the approaches...

5 minutes read.

Python md5() function

Python md5() function The md5() function in PHP calculates the md5 hash of a string. Syntax md5 ( string $str [, bool $raw_output] ) Parameter str(required)- This parameter specifies the string. raw_output(optional)- This parameter specifies a hex or binary output format: TRUE - Raw 16 character binary...

1 minute read.

How to check data type in python

The data type represents the nature of a variable; it determines what kind of data it can store and what operations can be carried out on it. There are five...

4 minutes read.

Python String rstrip() method

Python String rstrip() method The string.rstrip() method in Python returns a copy of the string with trailing characters removed. Syntax string.rstrip([chars]) Parameter chars:  This argument represents a string specifying the set of characters to be...

1 minute read.

Python MySQL Database Connection

In this article, you will be able to understand how to connect to a MySQL database through Python. We generally can use many methods or modules to connect to the database...

6 minutes read.

Python String ljust() method

Python String ljust() method The string.ljust() method in Python will left align the string, where the padding is done using the parameter fillchar (space is default). Syntax String.ljust(width[, fillchar]) Parameter width: This parameter represents the...

2 minutes read.

GUI Calendar using PyQt5 in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

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

3 minutes read.

Looping through Data Frame in Python

Iterate over Rows and Columns in Pandas Dataframe This tutorial aims to make us understand what Pandas in Python are, what Data Frame in Python is and its significance, what are...

4 minutes read.

Python Program to Find the gcd of Two Numbers

Introduction Greatest Common Divisor is the full form of gcd. The greatest common divisor, or GCD, of two numbers, is a value that can exactly divide the two digits and is...

5 minutes read.

Python Coroutine

Introduction In Python, Coroutines are defined as the special type of function that freely allows control to its caller without losing the state. Coroutines and generates are similar but coroutines consist...

3 minutes read.

*Args and **Kwargs in Python

Let’s know about ** (dual star / asterisk) and * (star / asterisk) are operators in Python. These stars are used in Python for parameters. Args and kwargs are special...

3 minutes read.

Python program to sort the array element into ascending order

Python program to sort the array element into ascending order In this example, we'll see how to sort the array elements in ascending order using a Python program. Sorting is a...

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

Selection Sort Using Python

Selection sort is a type of sorting algorithm which is based on sorting elements in increasing order or ascending order through comparison. This sorting technique does not take extra space...

3 minutes read.

Python Unit Test Cheat String

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.

Ternary operators in python

Starting from Python version 2.5, ternary operators are also known as Conditional operators. Using these operators, we can evaluate any problem based on a condition. It is an alternative and...

4 minutes read.

Decision Tree in Python

Decision Tree is one of the most essential algorithms in the area of machine learning for classification and regression. But let us first talk about the lifespan of every machine learning...

12 minutes read.

How to run a Python file in CMD

Introduction Today, let us learn about how to run a Python file using cmd. Cmd is nothing but command prompt. So first let us know how to run a Python code...

4 minutes read.

Python Set intersection_update() method

Python Set intersection_update() method The set.intersection_update() method in Python removes the items that is not present in both sets. It is different from the set.intersection() method, because the intersection()method returns a new set, with only  the common elements...

2 minutes read.