Bytes in Python 3.5

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

>>> x = os.urandom(16)
>>> print(x)
b'cCIp>\xfebUe\x02c\xc9\xbf5P\xe2'
>>> type(x)
bytes
>>> len(x)
16
>>> x[5]
254
>>> x.hex()
'634349703efe6255650263c9bf3550e2'
>>> x[0]      # ASCII code for 'c' is 99 (decimal)
99
>>> hex(x[0]) # ASCII code for 'c' is 63 (hexadecimal)
'0x63'
>>> hex(x[5])
'0xfe'

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.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s