[英]Compress/Decompress a String in Python 3
This question is tacked several times here and here but not answered completely.这个问题在这里和这里多次提出,但没有完全回答。 As decompression doesn't yield the original string.由于解压不会产生原始字符串。
>>> 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'
So decompression returns the original string included in "b''"所以解压返回包含在“b''”中的原始字符串
>>> p = str(y)
>>> p
"b'some string to test zlib'"
The same behavior by the way with gzip.顺便说一下,与 gzip 相同的行为。
y.decode('utf-8')
- the b is just an indication that this is a bytes
type being printed: 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'))
Output:输出:
some string to test zlib b'some string to test zlib'
some string to test zlib some string to test zlib
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.