Basics

Bytes and Bytearray

bytes and bytearray store binary data, not Unicode text.

Encode text when an external boundary needs bytes. UTF-8 uses one byte for ASCII characters and more than one byte for many other characters.

Source

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

Output

b'caf\xc3\xa9'
4 5
BYTES — FROZENb'\\x63\\x61\\x66'BYTEARRAY — MUTABLEbytearray(b'\\x63\\x61').append(0x66)
bytes is a frozen sequence of integers; bytearray is the mutable counterpart with append/extend/etc.

Decode bytes when the program needs text again. The decoder must match the encoding used at the boundary.

Source

print(data.decode("utf-8"))

Output

café

Indexing a bytes object returns an integer byte value, not a one-character bytes object.

Source

print(data[0])

Output

99

bytes is immutable. Use bytearray when binary data must be changed in place.

Source

packet = bytearray(b"py")
packet[0] = ord("P")
print(packet)

Output

bytearray(b'Py')

Notes

See also

Run the complete example

Example code

Expected output

b'caf\xc3\xa9'
4 5
café
99
bytearray(b'Py')

Execution time appears here after you run the example.