I'm trying to convert a binary I have in python (a gzipped protocol buffer object) to an hexadecimal string in a string escape fashion (eg. \xFA\x1C ..).
I have tried both
repr(<mygzipfileobj>.getvalue())
as well as
<mygzipfileobj>.getvalue().encode('string-escape')
In both cases I end up with a string which is not made of HEX chars only.
\x86\xe3$T]\x0fPE\x1c\xaa\x1c8d\xb7\x9e\x127\xcd\x1a.\x88v ...
How can I achieve a consistent hexadecimal conversion where every single byte is actually translated to a \xHH format ? (where H represents a valid hex char 0-9A-F)
The
\xhh
format you often see is a debugging aid, the output of therepr()
applied to a string with non-ASCII codepoints. Any ASCII codepoints are left a in-place to leave what readable information is there.If you must have a string with all characters replaced by
\xhh
escapes, you need to do so manually:If you need quotes around that, you'd need to add those manually too: