nik_rus nik_rus - 27 days ago 13
Python Question

Iteration through hex string

I have such binary string:

some_bytes = b'Q\x00\xfdM\xf6\x02\x14M\x03'


I would like to iterate through elements of this string (do not have to print, may be do some action with
x
):

for x in some_bytes:
print (x, end=' ')


The code above print
81 0 253 77 246 2 20 77 3
,

but I want to see
\Q \x00 \xfd M \xf6 \x02 \x14 M \x03


How can I do it? I can not do
chr()
, because it raises
UnicodeEncodeError
for
\xfd
.

wim wim
Answer
>>> for x in some_bytes:
...     print('{!r}'.format(bytes([x]))[2:-1], end=' ')
...     
...     
Q \x00 \xfd M \xf6 \x02 \x14 M \x03