Python 3.2中的HEX解码

ovg*_*vin 7 python codec python-3.x

在Python 2.x中,我能够这样做:

>>> '4f6c6567'.decode('hex_codec')
'Oleg'
Run Code Online (Sandbox Code Playgroud)

但是在Python 3.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)
Run Code Online (Sandbox Code Playgroud)

根据文档 hex_codec应提供"字节到字节的映射".所以这里正确使用了字节串的对象.

我怎样才能摆脱这个错误,以避免从十六进制编码的文本转换笨拙的变通方法?

Sve*_*ach 10

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

>>> codecs.decode(b"4f6c6567", "hex_codec")
b'Oleg'
>>> codecs.getdecoder("hex_codec")(b"4f6c6567")
(b'Oleg', 8)
Run Code Online (Sandbox Code Playgroud)

后一个函数似乎在文档中缺失,但有一个有用的文档字符串.

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