Bytes in Python 3.5

I’m working with os.urandom and I was puzzled by this output:

>>> x = os.urandom(16)
>>> print(x)
>>> type(x)
>>> len(x)
>>> x[5]
>>> x.hex()
>>> x[0]      # ASCII code for 'c' is 99 (decimal)
>>> hex(x[0]) # ASCII code for 'c' is 63 (hexadecimal)
>>> hex(x[5])

This question on StackOverflow clears things up greatly.

print(x) displays a “mixed hexadecimal/ascii” representation of the bytes object x. Bytes that correspond to ASCII characters are displayed as ASCII characters, and bytes that do not are displayed in hexadecimal notation. Which is a little bit confusing if you aren’t expecting it.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.