Show hex value for all bytes, even when ASCII characters are present

青春壹個敷衍的年華 提交于 2019-12-01 09:21:22
BrenBarn

There is no specific means of requiring any particular formatting (like \x) for a byte string. If you really need specific formatting, you could use something like the .hex() solution from this question, but wrap it with other code to insert the formatting you need. Another useful tool is the hex builtin function. For instance, if you want \x:

>>> x = bytes([67, 128])
>>> print(''.join(r'\x'+hex(letter)[2:] for letter in x))
\x43\x80

If you just need to be able to visually distinguish the bytes, using hex by itself may work for you (it uses 0x instead of \x):

>>> print(''.join(hex(letter) for letter in x))
0x430x80

There is not a way to make this the default behavior for byte strings. Whatever you do, you're going to have to write code that specifies the display format you want; you can't make Python automatically display printable bytes as \x escapes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!