打印字符串为hex literal python

时间:2014-02-21 23:10:50

标签: python string escaping

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

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

哪个python始终打印为:

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

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

3 个答案:

答案 0 :(得分:2)

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

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

由于.encode('hex')是对encode的误用,已在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

答案 1 :(得分:0)

您可以尝试这样的事情:

>>> x = '\x01\x41\x42\x43'
>>> x.encode('hex')
'01414243'

>>> x = r'\x01\x41\x42\x43'
>>> x
'\\x01\\x41\\x42\\x43'

>>> x = '\x01\x41\x42\x43'
>>> print " ".join(hex(ord(n)) for n in x)
0x1 0x41 0x42 0x43

答案 2 :(得分:0)

要实际打印出字符串〜literal(即您可以剪切并粘贴回代码以获取相同对象的内容),需要以下内容:

>>> x = '\x1\41\42\43'
>>> print "'" + ''.join(["\\"+ hex(ord(c))[-2:] for c in x]) + "'"
'\x1\41\42\43'