Quantcast
Channel: Active questions tagged utf-8 - Stack Overflow
Viewing all articles
Browse latest Browse all 1170

convert bytes to ascii if possible, hex otherwise

$
0
0

Imagine you have this byte array:

 b = bytes([0x00, 0x78, 0x6f, 0x58, 0x00, 0x4f, 0x30, 0x00]

and you want to print it in a somewhat readable way, using ASCII when possible and hex when not. You could simply use Python's built-in conversion:

>>> bb'\x00xoX\x00O0\x00'

But that's really not particularly readable. What I'd like is this:

00  x  o  X 00  O  0 00

...that is, a space and the ASCII char if the byte can be printed as ASCII or a two-digit hex value otherwise. I can think of some really awful ways to code this, but there must be a semi-elegant pythonic way. (An array of strings would be great, since you could join() them with a leading space as I've shown above.) How would you do it?


Viewing all articles
Browse latest Browse all 1170

Latest Images

Trending Articles



Latest Images