Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit bd866e9

Browse files
committed
Everybody hates this one :) (bytes indexing)
1 parent e6a1464 commit bd866e9

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

Doc/howto/pyporting.rst

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -367,6 +367,37 @@ To turn the warning into an exception, use the ``-bb`` flag instead::
367367
BytesWarning: Comparison between bytes and string
368368

369369

370+
Indexing bytes objects
371+
''''''''''''''''''''''
372+
373+
Another potentially surprising change is the indexing behaviour of bytes
374+
objects in Python 3::
375+
376+
>>> b"xyz"[0]
377+
120
378+
379+
Indeed, Python 3 bytes objects (as well as :class:`bytearray` objects)
380+
are sequences of integers. But code converted from Python 2 will often
381+
assume that indexing a bytestring produces another bytestring, not an
382+
integer. To reconcile both behaviours, use slicing::
383+
384+
>>> b"xyz"[0:1]
385+
b'x'
386+
>>> n = 1
387+
>>> b"xyz"[n:n+1]
388+
b'y'
389+
390+
The only remaining gotcha is that an out-of-bounds slice returns an empty
391+
bytes object instead of raising ``IndexError``:
392+
393+
>>> b"xyz"[3]
394+
Traceback (most recent call last):
395+
File "<stdin>", line 1, in <module>
396+
IndexError: index out of range
397+
>>> b"xyz"[3:4]
398+
b''
399+
400+
370401
``__str__()``/``__unicode__()``
371402
'''''''''''''''''''''''''''''''
372403
In Python 2, objects can specify both a string and unicode representation of

0 commit comments

Comments
 (0)