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.
1 2 3 4 5 6 7 8 9 10 11 12 |
import zlib long_text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' print('long_text', len(long_text)) long_text_compressed = zlib.compress(long_text.encode('utf-8')) print('long_text_compressed', len(long_text_compressed)) # long_text 445 # long_text_compressed 270 |
As we can see with this simplest example, the line size has been reduced by more than one and a half times.