On Wed, Mar 9, 2016 at 11:34 AM, Michael Torrie <torr...@gmail.com> wrote: > On 03/07/2016 05:45 PM, Chris Angelico wrote: >> On Tue, Mar 8, 2016 at 11:22 AM, BartC <b...@freeuk.com> wrote: >>> >>> (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. >> >> The default string in Py2 *is* a byte string. > > There are some interesting differences I found between a Python 2 string > (composed of bytes) and a Python 3 byte string, such as what you'd get > from calling read() on a file handle opened in binary mode. That is in > Python 2, indexing a string returns a string of length 1. In Python > 3.5, indexing a byte string returns a value, the equivalent of calling > ord() on the single byte string. This makes it a bit difficult to make > the code easily work between Python 2 and 3 and handle bytes. Any ideas > there?
As Steven commented, this is probably a design flaw in the Py3 bytes type, but it can't be changed now. For perfect compatibility, just slice: >>> b"asdf"[2:3] # Py2 'd' >>> b"asdf"[2:3] # Py3 b'd' Works in both versions, with the only difference being the repr. It's a bit clunky, but it does work. ChrisA -- https://mail.python.org/mailman/listinfo/python-list