打印字符串为hex literal python

我有很多预先存在的代码将字节数组视为字符串,即

In [70]: x = '\x01\x41\x42\x43'

哪个python始终打印为:

In [71]: x
Out[71]: '\x01ABC'

这使调试变得很麻烦,因为我打印的字符串看起来不像我的代码中的文字.如何将字符串打印为十六进制文字?

最佳答案 对于跨版本兼容的解决方案,请使用
binascii.hexlify

>>> import binascii
>>> x = '\x01\x41\x42\x43'
>>> print x
ABC
>>> repr(x)
"'\\x01ABC'"
>>> print binascii.hexlify(x)
01414243

因为.encode(‘hex’)是对编码的误用,并且已在Python 3中删除:

Python 3.3.1
Type "help", "copyright", "credits" or "license" for more information.
>>> '\x01\x41\x42\x43'.encode('hex')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: unknown encoding: hex
点赞