python通过zlib压缩和解压缩字符串

2022-04-24 00:00:00 字符串 压缩 和解

python通过zlib压缩和解压缩字符串,可以自定义压缩级别,级别越高压缩的约厉害,效率要低一些

"""
皮蛋编程(https://www.pidancode.com)
创建日期:2022/4/23
功能描述:python通过zlib压缩和解压缩字符串
"""

import zlib
originalString = b'hello pidancode.com pidancode.com pidancode.com pidancode.com pidancode.com pidancode.com  pidancode.com pidancode.com  pidancode.com pidancode.com  pidancode.com pidancode.com  pidancode.com pidancode.com  pidancode.com pidancode.com  pidancode.com pidancode.com  pidancode.com pidancode.com  pidancode.com pidancode.com  pidancode.com pidancode.com '
compressedString = zlib.compress(originalString, 9)  # 采用9级压缩
print(compressedString)
decompressedString = zlib.decompress(compressedString)
print(decompressedString)

输出结果如下:

b'x\xda\xcbH\xcd\xc9\xc9W(\xc8LI\xccK\xceOI\xd5K\xce\xcf\xa5\x12oT\x12\xc8\x03\x00\xa3\xbe\x805'
b'hello pidancode.com pidancode.com pidancode.com pidancode.com pidancode.com pidancode.com  pidancode.com pidancode.com  pidancode.com pidancode.com  pidancode.com pidancode.com  pidancode.com pidancode.com  pidancode.com pidancode.com  pidancode.com pidancode.com  pidancode.com pidancode.com  pidancode.com pidancode.com  pidancode.com pidancode.com '

代码在python3.9下测试通过,zlib压缩字符串,当字符串内重复字符出现次数越多,压缩效果越好

相关文章