Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In Python (3) at least, if a binary value has an ASCII representation, it is shown instead of the hexadecimal value. For instance, the binary value of 67 which is ASCII C is show as follows:

bytes([67]) # b'C'

Whereas for binary values without ASCII representations, they are shown in hex. I.E.

b'x0f'

Is there a way to force Python to show the binary values in their binary-hex form (if this is what it is called), even when there are ASCII representations?

Edit: By this I mean, something that starts with b'x',. This would make debugging easier when you are looking for specific bytes to be printed for instance.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
655 views
Welcome To Ask or Share your Answers For Others

1 Answer

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))
x43x80

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...