如何在Python3.2或更高版本中使用“hex”编码?

2024-05-16 20:42:04 发布

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

在Python2中,要获取字符串中十六进制数字的字符串表示形式,可以执行以下操作

>>> '\x12\x34\x56\x78'.encode('hex')
'12345678'

在Python3中,这不再有效(在Python3.2和3.3上进行了测试):

>>> '\x12\x34\x56\x78'.encode('hex')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: unknown encoding: hex

这里至少有one answer这样就说明hex编解码器已经在Python 3中被删除。但随后,according to the docs在Python 3.2中被重新引入,作为“字节到字节的映射”。

但是,我不知道如何让这些“字节到字节的映射”工作:

>>> b'\x12'.encode('hex')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'bytes' object has no attribute 'encode'

医生也没有提到这一点(至少在我看的地方没有提到)。我一定错过了一些简单的东西,但我看不出来是什么。


Tags: 字符串most字节stdincallencodefilelast
3条回答

使用^{}

>>> import base64
>>> base64.b16encode(b'\x12\x34\x56\x78')
b'12345678'

还有另一种使用^{}的方法:

>>> import binascii
>>> binascii.hexlify(b'\x12\x34\x56\x78')
b'12345678'

您需要通过^{}模块和^{}编解码器(或其hex别名(如果可用的话)*):

codecs.encode(b'\x12', 'hex_codec')

*来自3.4版中更改的文档:“还原二进制转换的别名”

相关问题 更多 >