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'

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts