【问题标题】:Compress/Decompress a String in Python 3在 Python 3 中压缩/解压缩字符串
【发布时间】:2020-10-01 16:49:44
【问题描述】:

这个问题被herehere 多次回答,但没有完全回答。由于解压不会产生原始字符串。

>>> s = "some string to test zlib"
>>> z = zlib.compress(s)
Traceback (most recent call last):
   File "<input>", line 1, in <module>
   TypeError: a bytes-like object is required, not 'str'
>>> z = zlib.compress(s.encode("utf8"))
>>> y = zlib.decompress(z)
>>> y
b'some string to test zlib'
>>> print (s, y)
some string to test zlib b'some string to test zlib'

所以解压返回“b''”中包含的原始字符串

>>> p = str(y)
>>> p
"b'some string to test zlib'"

顺便说一句,gzip 的行为相同。

【问题讨论】:

    标签: python gzip zlib


    【解决方案1】:

    y.decode('utf-8') - b 只是表示这是正在打印的bytes 类型:

    s = "some string to test zlib"
    z = zlib.compress(s.encode("utf-8"))
    y = zlib.decompress(z)
    y
    print (s, y)
    print (s, y.decode('utf-8'))
    

    输出:

    some string to test zlib b'some string to test zlib'
    some string to test zlib some string to test zlib
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-12
      相关资源
      最近更新 更多