A bytes object stores a fixed sequence of small integers, 0-255, rather than Unicode characters, making it the right type for binary data — file contents opened in binary mode, network payloads, image data — as opposed to str, which represents text. Converting between the two is explicit: str.encode() turns text into bytes using a given encoding (utf-8 by default), and bytes.decode() turns bytes back into text.
1Understanding Bytes
A bytes object stores a fixed sequence of small integers, 0-255, rather than Unicode characters, making it the right type for binary data — file contents opened in binary mode, network payloads, image data — as opposed to str, which represents text. Converting between the two is explicit: str.encode() turns text into bytes using a given encoding (utf-8 by default), and bytes.decode() turns bytes back into text.
Always encode/decode with an explicit encoding argument like 'utf-8' — relying on the platform default can silently produce different results on different operating systems.
data = "caf\u00e9".encode("utf-8")
print(data)
print(data.decode("utf-8"))2Practical Example
Here is a real-world application of Bytes showing how it is used in production Python code.
raw = bytes([72, 101, 108, 108, 111])
print(raw)
print(raw.decode("ascii"))3Best Practices
Follow these guidelines when working with Bytes:
1. Use bytes (or bytearray) for binary data and network/file I/O, not str
2. Always specify an explicit encoding, like 'utf-8', when calling encode()/decode()
3. Use bytearray instead of bytes when you need a mutable byte sequence, such as building up a buffer incrementally
Tip: Always encode/decode with an explicit encoding argument like 'utf-8' — relying on the platform default can silently produce different results on different operating systems.
data = "caf\u00e9".encode("utf-8")
print(data)
print(data.decode("utf-8"))