In the previous lesson, I spoke about typed arrays and strings. In this lesson, I’ll be showing you how to deal with binary data using binary arrays. Python provides two array types for dealing with binary data, the first of which is called
I can use subscripts to get at a specific byte within the
bytes object. Here’s the byte at position
3, which is the fourth item,
0x38, which when printed out is shown in decimal for a value of
gif_header object implements the
.__repr__() method, so you can see a representation of it inside of the REPL. The
b in front of this quote indicates that this is binary data for Python. The
GIF89a is because the first six characters are within readable ASCII range, so Python prints those as the ASCII values rather than the hexadecimal.
The remainder chunk are not printable characters in ASCII—
01 aren’t printable ASCII—so Python shows it as hexadecimal. As I mentioned before, a byte inside of the
bytes object has to be in the range of 0 to 255.
If you try to do something larger than that, you’ll get a
ValueError. In the error here, it says
range(0, 256). That’s because the Python
range() function is not inclusive, so that is
256 is outside the range.
bytes objects are immutable, so if you try to assign something to them, you’ll get an error.
Become a Member to join the conversation.