2

In Python 3, I have a binary string that I need to inspect the byte values of. Because some bytes are printable ASCII, the printed representation is hard to see.

data = b'\x08\x02\x10\x22\x0a\x0d\x00\x80\x3f\x15'
print('data is', len(data), 'bytes:', data)
# data is 10 bytes: b'\x08\x02\x10"\n\r\x00\x80?\x15'

I'd prefer to have full hex for each byte. Is there a simpler way to accomplish this than:

import binascii
import re
s = re.sub(r'..', r'\\x\g<0>', binascii.hexlify(data).decode('ascii'))
print(s)
# \x08\x02\x10\x22\x0a\x0d\x00\x80\x3f\x15

(Preferably one that uses a minimum number of import statements.)

1
  • 2
    Thanks @vaultah. I failed to find the duplicate because I didn't know that b'...' was a "byte array". Commented Dec 2, 2016 at 17:43

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.