Chapter 5. Bytes and Bytearray
I’m feeling a bit off.
Byte calling in sick
Python 3 introduced the following sequences of eight-bit integers, with possible values from 0 to 255, in two types:
-
An immutable sequence of 8-bit values:
bytes -
A mutable sequence of 8-bit values:
bytearray
This chapter covers the basics of both types. Chapter 20 goes into more detail on their real-life uses, including binary file formats. You’ll probably deal with binary data much less often than text strings.
The official Python docs have all the details on these data types. I’m including just the most common and useful in this chapter.
Here’s one way to think of bytes versus strings:
-
Bytes are like equally sized beads on a wire.
-
Strings are like a charm bracelet.
Bytes
Bytes, like strings, are immutable.
You can’t append, insert,
or change the contents of a bytes value
after you’ve created it.
Create with Quotes
A literal bytes object is surrounded by quotes like a text string,
but has a b right before the initial quote character.
Each byte in it is specified either as an ASCII character
or a two-character
hex literal:
>>>b1=b'ABC\x01\x02\x03\x41\x42\x43'>>>b1b'ABC\x01\x02\x03ABC'>>>b2=b'abc\x01\x02\x03\x61\x62\x63'>>>b2b'abc\x01\x02\x03abc'
This doesn’t mean that a bytes value can contain text characters.
It means that you can specify a byte with its hex value or its ASCII equivalent, if it has one. Python allows this ASCII shortcut for convenience on input and displaying ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access