all Python 3zlibfunction
zlib.compress()
compression
Compresses bytes with DEFLATE entirely in memory and returns bytes in the zlib format.
Syntax
zlib.compress(data, /, level=-1, wbits=15)
It accepts only bytes-like objects: encode a string first, or you get a TypeError. On short input the result is longer than the original — header and checksum add 6 bytes. The zlib format is not gzip: gzip.open and the gunzip tool cannot read it. level runs from 0 (no compression) to 9; the default -1 means 6, a sensible speed/size trade-off.
Examples
import zlib
text = 'привет, мир ' * 100
packed = zlib.compress(text.encode('utf-8'))
print(len(packed) < len(text.encode('utf-8'))) # → True
print(zlib.decompress(packed).decode('utf-8') == text) # → True
print(len(zlib.compress(b'a'))) # → 9 — короткие данные растут
import zlib
try:
zlib.compress('строка')
except TypeError as e:
print(type(e).__name__) # → TypeError — нужны bytes
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy