在Python 2中,要获得字符串中十六进制数字的字符串表示,您可以这样做
>>> '\x12\x34\x56\x78'.encode('hex')
'12345678'
Run Code Online (Sandbox Code Playgroud)
在Python 3中,它不再起作用(在Python 3.2和3.3上测试):
>>> '\x12\x34\x56\x78'.encode('hex')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
LookupError: unknown encoding: hex
Run Code Online (Sandbox Code Playgroud)
这里至少有一个答案提到hex在Python 3中已经删除了编解码器.但是,根据文档,它在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'
Run Code Online (Sandbox Code Playgroud)
而且文档也没有提到(至少不是我看的地方).我一定错过了一些简单的东西,但我看不出它是什么.
当我尝试在IronPython 2.0中 "导入simplejson"(或依赖于它的东西)时,我得到"LookupError:unknown encoding:hex".我该如何工作?