pythonpython-3.xpython-bytearray

Behavior of byte arrays indexing in python 3


Run across this:

import sys; print('Python %s on %s' % (sys.version, sys.platform))
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
b'\n' == b'\n'
True # well obviously
b'\n'[-1] == b'\n'
False # huh?
bytes(b'\n'[-1]) == b'\n'
False
b'\n'[-1] == 10
True

So it seems that when indexing in the byte array we get an integer value - why is this and how should I compare the values so I do not have to plugin the ascii value of the byte string element explicitly?


Solution

  • When you do b'\n', you create an instance of bytes that contains one value 10.
    When you access an element of an instance of bytes, an int is returned as expected (a byte is an 8 bits unsigned int).

    Thus b'\n'[-1] == b'\n' being False makes sense, the value 10 is different from a bytes instance containing one byte

    When you use the bytes constructor with an int, it creates a zero-filled bytes instance of the size you gave as input (python doc).

    Thus bytes(b'\n'[-1]) == b'\n' also makes sense, a list of 10 bytes of value 0 is not equal to a list of only byte of value 10.

    Hope it helps