Weird list conversion

Erik python at lucidity.plus.com
Sun Dec 13 15:28:16 EST 2015


On 13/12/15 20:05, KP wrote:
> On Sunday, 13 December 2015 11:57:57 UTC-8, Laura Creighton  wrote:
>> In a message of Sun, 13 Dec 2015 11:45:19 -0800, KP writes:
>>> Hi all,
>>>
>>> f = open("stairs.bin", "rb") data = list(f.read(16)) print data
>>>
>>> returns
>>>
>>> ['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00',
>>> '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00']
>>>
>>> The first byte of the file is 0x3D according to my hex editor, so
>>> why does Python return '=' and not '\x3D'?
>>>
>>> As always, thanks for any help!
>>
>> 0x3d is the ascii code for '='
>
> I am aware of that - so is the rule that non-printables are returned
> in hex notation whereas printables come in their ASCII
> representation?

No, what is _returned_ is a list of one-byte strings.

When you call "print", then the list class's __repr__() method is called 
which in turn calls the contained objects' __repr__() methods in turn - 
it is those methods (in this case, they are all the string class's) 
which is deciding to render ASCII printable characters as just their 
value and ASCII non-printable characters using their hex notation.

E.



More information about the Python-list mailing list