[Tutor] os.urandom()

Alan Gauld alan.gauld at btinternet.com
Sun Aug 8 10:05:19 CEST 2010


"Richard D. Moores" <rdmoores at gmail.com> wrote

> So if os.urandom() had been written so that it printed only hex,
> b'l\xbb\xae\xb7\x0ft' would have been
>
> b'\x6c\xbb\xae\xb7\x0f\x74' , right?

Yes except that its not urandomthat is printing those values.
urandom returns a string of bytes.
Its the Python interpreter calling the repr() function on
those bytes that is deciding to print either hex or character.
Try this:

>>> '\x6c\xbb\xae\xb7\x0f\x74'
'l\xbb\xae\xb7\x0ft'
>>> print '\x6c\xbb\xae\xb7\x0f\x74'
l╗«À☼t
>>>

In the first case its the repr() of the string that gets
printed in the second its the str(). Its the conversion
function that determines what gets printed not urandom()

> How were we supposed to know that all the hexes have 2 digits? How 
> did you?

Simple arithmetic...
Its the hex representation of a byte. A byte is 8 bits long.
A hex digit represents 4 bits (0000-1111) so you need 2 hex digits to
represent 8 bits or one byte.

Alan G. 




More information about the Tutor mailing list