在python 3中压缩字符串? [英] compress a string in python 3?
本文介绍了在python 3中压缩字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不明白在2.X中,它起作用了:
I don't understand in 2.X it worked :
import zlib
zlib.compress('Hello, world')
现在我有一个:
zlib.compress("Hello world!")
TypeError: must be bytes or buffer, not str
如何压缩我的字符串?问候比西尔
How can i compress my string ? Regards Bussiere
推荐答案
这是为了强制您实际上具有已定义的编码.
This is meant to enforce that you actually have a defined encoding.
zlib.compress("Hello, world".encode("utf-8"))
b'x\x9c\xf3H\xcd\xc9\xc9\xd7Q(\xcf/\xcaI\x01\x00\x1b\xd4\x04i'
zlib.compress("Hello, world".encode("ascii"))
b'x\x9c\xf3H\xcd\xc9\xc9\xd7Q(\xcf/\xcaI\x01\x00\x1b\xd4\x04i'
否则,同一字符串可以描述不同的字节序列.但这实际上是由zlib编码的字节序列.
The same string could describe different byte sequences otherwise. But it is actually a byte sequence that will be encoded by zlib.
>>> zlib.compress("Hello, wørld".encode("utf-16"))
b'x\x9c\xfb\xff\xcf\x83!\x95!\x07\x08\xf3\x19t\x18\x14\x18\xca\x19~0\x14\x01y)\x0c\x00n\xa6\x06\xef'
>>> zlib.compress("Hello, wørld".encode("utf-8"))
b"x\x9c\xf3H\xcd\xc9\xc9\xd7Q(?\xbc\xa3('\x05\x00#\x7f\x05u"
这篇关于在python 3中压缩字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文