×

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

Important Difference between Python 2.x and Python 3.x with Example

The comparison between Python 2 and Python 3 is given in the article that follows. Python is a computer language that can perform more tasks than other languages and is...

5 minutes read.

Python hash() function

Python hash() function The hash() function in Python returns the hash value of the object (if it has one).  Syntax hash(object) Parameter obj : This parameter represents the object which we need to convert into hash. Return This...

1 minute read.

Reverse a sentence In Python

Introduction The built-in reverse() function is not supported by the Python string library. As we know, a Python string is defined as a set of Unicode characters and Python provides various...

4 minutes read.

Run exec python from PHP

PHP (which is a recursive abbreviation for PHP Hypertext Preprocessor) is one of the most broadly involved web improvement innovations on the planet. PHP code utilized for creating sites and...

4 minutes read.

An Introduction to Subprocess in Python with Examples

Subprocess in Python By starting new processes, the Python function subprocess is utilized to run extra programs and applications. It makes it possible to run brand-new apps straight from a Programming...

6 minutes read.

Cx_Oracle Python with Example

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

6 minutes read.

Python Linked List

Linked List Linked lists non-contiguous linear data structure which is made up of nodes and used to store value and a pointer pointing to the next node. It is linked with...

6 minutes read.

Best Way to Learn Python for Free

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. Learning Python is a step towards coding. Python gets...

5 minutes read.

Curdir Python

Python Programming Language 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...

3 minutes read.

Creating Web Application in python

Web Application :  Web Application is an application software that runs in web browser . Software programs will run on operating system. Whereas Web Applications will run on World Wide Web...

5 minutes read.

Python Namespace

In python, the namespace is a very important concept that should be understood before using any function or variables. When we write code, we often use variables, libraries, functions, modules, etc....

4 minutes read.

Write a String 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...

5 minutes read.

Salary of Python Developers in India

In this tutorial, we will understand who python developers are and what is their salary when they work in India. Python Developers Python Developers are the people who are involved in designing...

4 minutes read.

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

Python Program to Find the Greatest Among Three Numbers

Python Program to find the greatest among three numbers We have many approaches to get the largest of three numbers, and here we will discuss a few of them. This python...

2 minutes read.

Sort a dataframe based on a column in Python

Sorting the dataframe based on a column requires pandas which is An open-source library called Python Pandas is described as offering high-performance data processing in Python. For both professionals and...

4 minutes read.

Python bin() function

Python bin() function The bin() function in Python returns the binary version for the specified integer. Syntax bin(x) Parameter n: This parameter represents an integer or int value. Return This function returns a binary string for the specified integer...

1 minute read.

Python maketrans() function

Introduction A static method is the string maketrans() one. It is used to make a one-to-one mapping between a string's character and its translation, i.e., to define the list of characters...

5 minutes read.

Python Bitwise Operators

When used with variables and objects in an expression, operators are tokens that carry out calculations. The variables and items to which the computation is applied are known as operands....

5 minutes read.

Alexa Python

The cloud-based voice assistant renders text into speech in a female voice. Alexa is a virtual assistant released by Amazon. Using itself as a system for home automation, Alexa can...

4 minutes read.