Python bytes
bytes is an immutable sequence of integers in the range 0-255, typically used for binary data such as files, network protocols, and text encoded as UTF-8 or other encodings.
Creating bytes
You can create bytes from a literal, by encoding a string, or from an iterable of integers.
Example
Encode a string to bytes and specify an encoding:
s = "café"
b = s.encode("utf-8")
print(b) # b'caf\xc3\xa9'
print(list(b)) # [99, 97, 102, 195, 169]
Try it Yourself »
Working with bytes
Bytes are immutable and support many sequence operations like indexing, slicing, iteration, and membership tests.
Example
Index, slice, and iterate:
b = b"ABCDEF"
print(b[0]) # 65
print(b[1:4]) # b'BCD'
for byte in b:
print(byte, end=" ")
Decoding bytes
Use bytes.decode() to get back a string:
Example
b = b"caf\xc3\xa9"
print(b.decode("utf-8")) # café
See also
Reference: bytes()