struct module in Python

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to learn about the struct module. Let's dive into the tutorial.

The module struct is used to convert the native data types of Python into string of bytes and vice versa. We don't have to install it. It's a built-in module available in Python3.

The struct module is related to the C languages. We have to know the notations used in C to represent various data type to work with struct module. Let's see some of them.

Data TypeFormat Character
inti
charc
strings
floatf

Let's see how to convert the Python data types into bytes.

struct.pack()

The method struct.pack() is used to convert the data types into bytes. It takes multiple arguments based on the first string.

We have to pass the first string with format characters as mention in the above table. We can pass any arguments as we want. Let's see some examples.

  • struct.pack('14s i', b'Tutorialspoint', 2020)
  • struct.pack('i i f 3s', 1, 2, 3.5, b'abc')

Let's convert the above examples into bytes.

Example

 Live Demo

# importing the struct module
import struct
# converting into bytes
print(struct.pack('14s i', b'Tutorialspoint', 2020))
print(struct.pack('i i f 3s', 1, 2, 3.5, b'abc'))

Output

If you run the above code, then you will get the following result.

b'Tutorialspoint\x00\x00\xe4\x07\x00\x00'
b'\x01\x00\x00\x00\x02\x00\x00\x00\x00\x00`@abc'

struct.unpack()¶

We have another method struct.unpack() that converts bytes to native Python data types. It takes two arguments, the first one is similar to the pack() method and the second one is the result of struct.pack() method.

The method struct.unpack() always returns a tutple.

Example

 Live Demo

# importing the struct module
import struct
# converting into bytes
converted_bytes = struct.pack('14s i', b'Tutorialspoint', 2020)
# converting into Python data types
print(struct.unpack('14s i', converted_bytes))

Output

If you run the above code, then you will get the following result.

(b'Tutorialspoint', 2020)

Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

raja
Published on 11-Jul-2020 07:56:42
Advertisements