File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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'''''''''''''''''''''''''''''''
372403In Python 2, objects can specify both a string and unicode representation of
You can’t perform that action at this time.
0 commit comments