Using Python, how do I display a bytes object as a readable string?
Feb 11, 2021
asked by anonymous
Question / Issue:
> b1 = b'\x0c\x00\x01\x02\x00\x00\x01\x02\x02\x00\x00\x00'
> print(b1)
b'\x0c\x00\x01\x02\x00\x00\x01\x02\x02\x00\x00\x00'
> b1.decode()
'\x0c\x00\x01\x02\x00\x00\x01\x02\x02\x00\x00\x00'
I would like
'0c 00 01 02 00 00 01 02 02 00 00 00'
Responses:
Date: Feb. 11, 2021
Author: Mind Chasers
Comment:
One way is to use python3.8 or higher and memoryview as shown below:
b1 = b'\x0c\x00\x01\x02\x00\x00\x01\x02\x02\x00\x00\x00'
m1 = memoryview(b1)
m1.hex(' ')
'0c 00 01 02 00 00 01 02 02 00 00 00'