Python 3.6.3中的zlib压缩

3

我正在尝试使用zlib在Python 3.6.3中压缩字符串,但是出现了错误(TypeError:需要类似字节的对象,而不是'str'),它应该在Python 2.7及以下版本上运行,这是我的简单代码:

import zlib
a='hellohellohelloheeloohegregrf'
b=zlib.compress(a)
print(b)
1个回答

6
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”对象。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接