Pyhon 2.x or 3.x, which is faster?

MRAB python at mrabarnett.plus.com
Mon Mar 7 19:47:44 EST 2016


On 2016-03-08 00:22, BartC wrote:
> On 07/03/2016 23:40, Chris Angelico wrote:
>> On Tue, Mar 8, 2016 at 9:39 AM, BartC <bc at freeuk.com> wrote:
>
>>> I'm using it because this kind of file reading in Python is a mess. If I do
>>> a read, will I get a string, a byte sequence object, a byte-array, or
>>> array-array, or what?
>>
>> Uhh.... you'll get either a text string or a byte string, depending on
>> whether you opened the file as text or binary. Where's the mess?
>
> (Is a byte string the same as a byte array? Is a byte array the same as
> an array.array? If I remove this line from my code, where 'data' has
> just been read from a file:
>
>      data=array.array('B',data)
>
> then it still works - Python 3. But not on Python 2. If I do .read on a
> binary file I get a byte string in Python 3, but a string in Python 2.
> That sort of mess.
>
In Python 2, an unmarked string literal _is_ a bytestring; in Python 3, 
an unmarked string literal is Unicode.



> And how do I write that deceptively simple header on the output file
> without array.array because I tried all sorts:
>
>      f = open(file+".ppm", "wb")
>      s="P6\n%d %d\n255\n" % (hdr.width, hdr.height)
>      sbytes=array.array('B',list(map(ord,s)))
>      f.write(sbytes)
>
You don't need to use array.array:

     sbytes = bytes(map(ord, s))

In Python 3.5, you can use '%' with a bytestring:

     s = b"P6\n%d %d\n255\n" % (hdr.width, hdr.height)

[snip]




More information about the Python-list mailing list