7

I'm trying to understand the way Python displays strings representing binary data.

Here's an example usingos.urandom

In [1]: random_bytes = os.urandom(4)In [2]: random_bytesOut[2]: '\xfd\xa9\xbe\x87'In [3]: random_bytes = os.urandom(4)In [4]: random_bytesOut[4]: '\r\x9eq\xce'

In the first example ofrandom_bytes, after each \x there seem to be values in hexadecimal form: fd a9 be 87.

In the second example, however, I don't understand why'\r\x9eq\xce' is displayed.

Why does Python show me these random bytes in this particular representation? How should I interpret'\r\x9eq\xce'?

askedFeb 19, 2012 at 15:18
Kim's user avatar

2 Answers2

12

It's only using the\xHH notation for characters that are (1) non-printable; and (2) don't have a shorterescape sequence.

To examine the hex codes, you could use thebinascii module:

In [12]: binascii.hexlify('\r\x9eq\xce')Out[12]: '0d9e71ce'

As you can see:

  • \r is the same as\x0d (it's the ASCII Carriage Return character, CR);
  • q is the same as\x71 (the latter is the hexASCII code of the former).
answeredFeb 19, 2012 at 15:24
NPE's user avatar
Sign up to request clarification or add additional context in comments.

1 Comment

"It's only using the \xHH notation for characters that are (1) non-printable; and (2) don't have a shorter escape sequence." Why is it so? Is there a way to prevent this, and see the hex representation instead of printable character or the escape sequence?
3

\r is a carriage return, q is the q character - you should refer to their ASCII values (0x0d and 0x71)

Whenever python can - it will display the corresponding ASCII character, you'll only see \x when it can't (usually when the byte is higher than 0x79)

answeredFeb 19, 2012 at 15:24
Ofir's user avatar

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.