user153882
user153882

Reputation: 347

Python: How to use print without converting to ASCII

I have a mixture of hex and some numbers, I want to print:

"\x00\x00\x00\x00\x00\x00\x00\x9b\x00\x00\x00\xebS\xc3\x90\x08\x00\x00\x00\xed\x9b\xbcX\x00\x00\x00\x00\x00\x00\x00\x00\x820416e9c05a9942f67d1ee0b53642e79fae45af47a3afceb6a21a94c8487e1290645d789253fb05a1a8ee529b2cb4de2877fbbe11aa24a64dc20450ff722e41f92d\xed\x18\x03\x00\x00\x00\x00\x00"

When I print, it converts it to ASCII, how do I keep the format including the slash signs. I tried

' '.join(hex(ord(i)) for i in binascii.unhexlify('deadbeef'))

But it ends up removing the backslash or if I tried adding it, it would add to the ones in the middle. I just want to print exactly this, I can do this in C, why is it so difficult in Python!

Upvotes: 4

Views: 1374

Answers (2)

KMR
KMR

Reputation: 808

Probably the easiest way to get the functionality you want is to use raw string literals (see the String Literal documentation)

In short, prepend the string declaration with either r or R:

>>> str = r"\x00\x00\x00\x00\x00\x00\x00\x9b\x00\x00\x00\xebS\xc3\x90\x08\x00\x00\x00\xed\x9b\xbcX\x00\x00\x00\x00\x00\x00\x00\x00\x820416e9c05a9942f67d1ee0b53642e79fae45af47a3afceb6a21a94c8487e1290645d789253fb05a1a8ee529b2cb4de2877fbbe11aa24a64dc20450ff722e41f92d\xed\x18\x03\x00\x00\x00\x00\x00"
>>> print str
\x00\x00\x00\x00\x00\x00\x00\x9b\x00\x00\x00\xebS\xc3\x90\x08\x00\x00\x00\xed\x9b\xbcX\x00\x00\x00\x00\x00\x00\x00\x00\x820416e9c05a9942f67d1ee0b53642e79fae45af47a3afceb6a21a94c8487e1290645d789253fb05a1a8ee529b2cb4de2877fbbe11aa24a64dc20450ff722e41f92d\xed\x18\x03\x00\x00\x00\x00\x00

Upvotes: 0

Yeo
Yeo

Reputation: 11814

use raw string r'hello world'

x = r"\x00\x00\x00\x00\x00\x00\x00\x9b\x00\x00\x00\xebS\xc3\x90\x08\x00\x00\x00\xed\x9b\xbcX\x00\x00\x00\x00\x00\x00\x00\x00\x820416e9c05a9942f67d1ee0b53642e79fae45af47a3afceb6a21a94c8487e1290645d789253fb05a1a8ee529b2cb4de2877fbbe11aa24a64dc20450ff722e41f92d\xed\x18\x03\x00\x00\x00\x00\x00"`
print(x)

Upvotes: 6

Related Questions