[SOLVED] How to compress or compact a string in Python


I’m making a python “script” that sends a string to a webservice (in C#). I NEED to compress or compact this string, because the bandwidth and MBs data is LIMITED (yeah, in capitals because it’s very limited).

I was thinking of converting it into a file and then compressing the file. But I’m looking for a method to directly compress the string.

How can I compress or compact the string?


How about zlib?

import zlib

a = "this string needs compressing"
a = zlib.compress(a.encode())
print(zlib.decompress(a).decode())  # outputs original contents of a

You can also use sys.getsizeof(obj) to see how much data an object takes up before and after compression.

Answered By – hmir

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

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