🎓 A1Learner
🔍

Python Bytes & Bytearray

Bytes is an immutable sequence of numbers, each from 0 to 255. Bytearray is the mutable twin of bytes.

Make bytes with a b prefix

Each item in bytes is a number. Index 0 of b"hello" is the number for h.

data = b"hello"
print(data)
print(data[0])
print(len(data))

Build bytes from numbers

bytes() can build from a list of numbers. Here 65, 66, and 67 are the codes for A, B, and C.

data = bytes([65, 66, 67])
print(data)

Encode text into bytes

The letter é takes two bytes in UTF-8. So four characters become five bytes.

text = "café"
data = text.encode("utf-8")
print(data)
print(len(text))
print(len(data))

Decode bytes back into text

decode() reverses encode(). The result is a normal string again.

data = b"hello"
text = data.decode("utf-8")
print(text)
print(text + " world")

Change a bytearray in place

A bytearray lets you swap one byte. Number 98 is the code for b.

buf = bytearray(b"cat")
buf[0] = 98
print(buf)
print(bytes(buf))

Bytes cannot change in place

The same swap on bytes fails. Bytes is immutable, just like a string.

data = b"cat"
data[0] = 98

Example

word = "naïve"
data = word.encode("utf-8")
print("Characters:", len(word))
print("Bytes:", len(data))
print(data)
buf = bytearray(data)
buf[0] = 78
print(bytes(buf).decode("utf-8"))

Key points

  • Bytes: an immutable sequence of numbers, each from 0 to 255
  • Bytearray: the mutable twin of bytes, changeable in place
  • Use encode() to turn a string into bytes
  • Use decode() to turn bytes back into a string
  • UTF-8: a widely used set of rules for storing characters as bytes
  • One character can take more than one byte in UTF-8
  • Files and networks move bytes.

In this example, word holds the text naïve. It has five characters. encode("utf-8") turns it into bytes. The ï takes two bytes, so the bytes have length six. Next the code makes a bytearray from those bytes. A bytearray can change in place, so buf[0] = 78 swaps the first byte. Number 78 is the code for a capital N. Last, bytes(buf) freezes the result back into bytes. decode("utf-8") turns it into text again, and it prints Naïve.

Note

Text and bytes are different types in Python.

Mixing them up raises TypeError instead of guessing.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does "hi".encode("utf-8") return?