Python: how to zip a text string

In order to reduce the size of a long text string, for example, to minimize traffic when sending some text data over the Internet, it can be compressed before sending and unzipped after receiving. The size of transmitted data is significantly reduced in comparison with sending text strings in their original format.

To zip a text string in memory, we can use the “zlib” module.

Let’s use the “compress” function to compress the string. This function takes a byte string as an input parameter and returns the compressed byte string.

As we can see with this simplest example, the line size has been reduced by more than one and a half times.

Since “zlib.compress” takes a byte string as an input argument, we pre-encoded the source text into a set of UTF-8 bytes with the “encode” function.

As a result of compression, we also received a byte string. If the data transfer protocol requires the transfer of a text string, we can get it by encoding the result in base64.

As we can see, the size of the line has increased, but still remains smaller than the size of the original text string. With longer texts, the difference between compressed and uncompressed texts will increase.

To get the original text from the compressed, we need to decode and unzip it. Let’s do the reverse operation: