【问题标题】:python 3.6.3. zlib compression蟒蛇 3.6.3。 zlib 压缩
【发布时间】:2018-11-19 09:49:55
【问题描述】:

我正在尝试使用 zlib 压缩 python 3.6.3 中的字符串,但出现错误(TypeError: a bytes-like object is required, not 'str'),它应该适用于 python 2.7- 版本,这是我的简单代码:

import zlib
a='hellohellohelloheeloohegregrf'
b=zlib.compress(a)
print(b)

【问题讨论】:

    标签: python-3.x compression zlib


    【解决方案1】:
    import zlib
    a='hellohellohelloheeloohegregrf'
    b=zlib.compress(a.encode("utf-8"))
    print(b)
    

    替代方案:

    import zlib
    a= b'hellohellohelloheeloohegregrf'
    b=zlib.compress(a)
    print(b)
    

    Python2.x 中,此字符串文字称为str 对象,但它存储为bytes

    Python3.x 中,此字符串文字是str 对象,其类型为Unicode。因此,需要在其前面加上b 或使用.encode 来获取bytes 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多