Python 3.2 中的十六进制解码

2024-09-28 20:20:20 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python2.x中,我能够做到:

>>> '4f6c6567'.decode('hex_codec')
'Oleg'

但在Python3.2中,我遇到了以下错误:

>>> b'4f6c6567'.decode('hex_codec')
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    b'4f6c6567'.decode('hex_codec')
TypeError: decoder did not return a str object (type=bytes)

根据docshex_codec应该提供“字节到字节的映射”。所以这里正确使用了byte string的对象。

如何消除此错误,以避免从十六进制编码的文本转换时出现难以处理的工作区?


Tags: most字节错误linecallcodecfilelast
1条回答
网友
1楼 · 发布于 2024-09-28 20:20:20

在Python 3中,使用bytes.decode()方法将原始字节解码为Unicode,因此必须使用codecs.getdecoder()codecs.decode()codecs模块获取解码器,用于bytes到-bytes编码:

>>> codecs.decode(b"4f6c6567", "hex_codec")
b'Oleg'
>>> codecs.getdecoder("hex_codec")(b"4f6c6567")
(b'Oleg', 8)

文档中似乎缺少后一个函数,但它有一个有用的docstring。

您可能还想看看binascii.unhexlify()

相关问题 更多 >