compress a string in python 3?

只愿长相守 提交于 2020-12-08 07:06:32

问题


I don't understand in 2.X it worked :

import zlib
zlib.compress('Hello, world')

now i have a :

zlib.compress("Hello world!")
TypeError: must be bytes or buffer, not str

How can i compress my string ? Regards Bussiere


回答1:


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'

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"



回答2:


In python 2.x strings are bytes string by default. In python 3.x they are unicode strings.

Compressing needs a byte string.



来源:https://stackoverflow.com/questions/3839323/compress-a-string-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!