Home > Software engineering >  Python print single byte as char
Python print single byte as char

Time:01-08

I have a long array of bytes and I need to carefully inspect the values at each position. So I want to print it in two columns with byte number and byte value. How can this be done?

Example:

bytes = b'hola\x00chau'

print(bytes)
for i,byte in enumerate(bytes):
    print(i,byte)

Desired output:

b'hola\x00chau'
0 h
1 o
2 l
3 a
4 \x00
5 c
6 h
7 a
8 u

The code actually prints the bytes as integers.

CodePudding user response:

Found the answer after some experimentation:

bytes = b'hola\x00chau'

print(bytes)
for i,byte in enumerate(bytes):
    print(i,byte.to_bytes(1,'big'))

produces

b'hola\x00chau'
0 b'h'
1 b'o'
2 b'l'
3 b'a'
4 b'\x00'
5 b'c'
6 b'h'
7 b'a'
8 b'u'

CodePudding user response:

If you don't want to convert back and forth,

data = b'hola\x00chau'

for i in range(len(data)):
    print(i, data[i:i 1].decode("ascii"))

produces

0 h
1 o
2 l
3 a
4 
5 c
6 h
7 a
8 u

and

for i in range(len(data)):
    print(i, data[i:i 1])

produces

0 b'h'
1 b'o'
2 b'l'
3 b'a'
4 b'\x00'
5 b'c'
6 b'h'
7 b'a'
8 b'u'
  • Related