Jacob Valenta
Jacob Valenta

Reputation: 6769

Convert ASCII characters to hex escaped strings

I was reading in a file from Python. I opened this file and used 'rb' to read the bytes. When I read them off, say:

f.read(1)

it would output something like this

b'\x50'

So my question is, when I tried a longer string like this

f.read(24)

I got this:

b'R\x00S\x00S\x00Q\x00S\x00O\x00N\x00P\x00S\x00M\x00R\x00P\x00

You notice that there are ASCII characters mixed into the hex. I would want the R to be displayed as \x52.

How do I do that?

Upvotes: 2

Views: 1858

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799210

print(''.join('\\x%02x' % c for c in B))

Upvotes: 6

Related Questions