Python | Compressing String Using zlib

If for some reason in your python code, you need to compress some string value as some encoding then using zlib module is best option.
Let’s see how Python String can be encoded/compressed using zlib module.

Python Code for Compressing String using zlib Module
Do note here that before passing on string to compress function it need to be a byte object, not string itself. That’s why using encode() function, string first need to be encoded and then only can be compressed.

# Python Code for Compressing String using zlib module
import zlib

# Defining a Python String
a_string = "Computer Science Hub"

# Compressing a Python String
compressed_string = zlib.compress(a_string.encode())

# Decompressing a Python String
decompressed_string = zlib.decompress(compressed_string)

# Printing out original string, compressed string, decompressed string
print("original:", repr(a_string))
print("compressed message:", repr(compressed_string))
print("decompressed message:", repr(decompressed_string))

Output of Above Code

original: 'Computer Science Hub'
compressed message: b'x\x9cs\xce\xcf-(-I-R\x08N\xceL\xcdKNU\xf0(M\x02\x00O\xcc\x07i'
decompressed message: b'Computer Science Hub'

Leave a Comment