[Tutor] os.urandom()

Steven D'Aprano steve at pearwood.info
Sun Aug 8 10:15:42 CEST 2010


On Sun, 8 Aug 2010 03:57:39 pm Richard D. Moores wrote:

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

os.urandom() doesn't *print* anything. It RETURNS a byte string. What 
you do with it is your business.

In your case, you fail to save the return result in a variable, or put 
it in a list, or do anything else with it, so the interactive 
interpreter prints it. All that the interpreter sees is bytes. They 
could have come from a hard-coded literal:

>>> 'l\xbb\xae\xb7\x0ft'
'l\xbb\xae\xb7\x0ft'

or a list:

>>> L = ['l\xbb\xae\xb7\x0ft', None, None]
>>> L[0]
'l\xbb\xae\xb7\x0ft'

or some function call:

>>> (lambda c: c + '\xbb'[:] + '\xae\xb7' + 1*'\x0ft')('l')
'l\xbb\xae\xb7\x0ft'


(The above examples are from Python 2.5 rather than 3.1, where byte 
strings aren't flagged with a leading b.)



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

Because that's what they do. Numbers between 0 and 255 inclusive can be 
written in two hex digits 00..FF, just like numbers between 0 and 99 
inclusive can be written in two decimal digits.



-- 
Steven D'Aprano


More information about the Tutor mailing list