lzstring Python Library
lzstring is a Python port of the JavaScript lz-string library, providing efficient in-memory compression and decompression of strings. It supports various encoding formats like Base64, UTF16, and raw binary, making it suitable for compact data storage or transfer, especially when interoperating with JavaScript applications. The current version is 1.0.4, and the library is mature and stable with infrequent updates.
Common errors
-
AttributeError: 'LZString' object has no attribute 'compress_to_base64'
cause Attempting to call a method using snake_case naming convention when `lzstring` methods follow camelCase.fixUse the correct camelCase method name, e.g., `lzs.compressToBase64()` instead of `lzs.compress_to_base64()`. -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x... in position ...: invalid start byte
cause Attempting to decompress corrupted data, data not compressed by `lzstring`, or passing a byte string that isn't valid UTF-8 to a method expecting a Python `str` after some internal operation.fixVerify the integrity and origin of the compressed data. Ensure it was compressed using `lzstring` (or a compatible JavaScript `lz-string`) and that you are using the correct decompression method. If the error occurs on input, ensure your input is a valid Python `str`.
Warnings
- gotcha When interoperating with the JavaScript lz-string library or storing compressed data, ensure you use the correct pair of compression and decompression methods. For example, data compressed with `compressToBase64` must be decompressed with `decompressFromBase64`.
- gotcha The `lzstring` library expects Python `str` objects (Unicode) as input for compression. While it handles internal UTF-8 encoding, providing raw `bytes` without explicit decoding can lead to `TypeError` or incorrect compression/decompression results.
Install
-
pip install lzstring
Imports
- LZString
from lzstring import LZString
Quickstart
from lzstring import LZString
lzs = LZString()
original_string = "Hello World! This is a test string for compression."
# Compress to a standard lz-string format
compressed_data = lzs.compress(original_string)
print(f"Compressed (raw): {compressed_data[:50]}...")
decompressed_data = lzs.decompress(compressed_data)
print(f"Decompressed (raw): {decompressed_data}")
assert original_string == decompressed_data
# Compress to Base64 (common for web transfer)
compressed_b64 = lzs.compressToBase64(original_string)
print(f"Compressed (Base64): {compressed_b64[:50]}...")
decompressed_b64 = lzs.decompressFromBase64(compressed_b64)
print(f"Decompressed (Base64): {decompressed_b64}")
assert original_string == decompressed_b64