I am playing around with the bytearray type in python 2.7.3 and noticed this weird behaviour:
Passing an integer argument to its constructor creates a bytearray of size equal to the integer filled with zero bytes:
>>> s = bytearray(15)
>>> s
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
However, if I attempt to create a bytearray with bytes set manually by me, the constructor seems to ignore/skip some of the bytes I create:
>>> s = bytearray(b'\x34\x78\x98\xFF\xFF')
>>> s
bytearray(b'4x\x98\xff\xff')
Why is this happening? Is this a bug? Or am I missing something? The python documentation is not very enlightening.
Nothing strange is happening, all the bytes are still there. Relax! 🙂
The confusion stems from the fact that the representation is slightly optimized: bytes whose values represent printable characters are printed as those characters. This makes them take just a single character in the output rather than four.
It’s doing just what it says:
\x34is the character4, which is why the buffer starts with a ‘4‘\x78is the characterx, which is why there’s an ‘x‘ after the ‘4‘\x98\xff\xffare all kept as-is.Note that
len(s)prints 5.Epic graphical representation: