Glossary

Bytes

The bytes type represents an immutable sequence of integers in the range 0–255, used for binary data — file contents, network packets, images, encoded text, and any raw byte stream. Bytes literals use the b prefix: b"hello", b'\x00\xff'. The mutable counterpart is bytearray, which supports in-place modification.

The most common interaction with bytes is encoding and decoding text. "hello".encode("utf-8") converts a string to bytes; b"hello".decode("utf-8") converts bytes back to a string. File objects opened in binary mode (open(path, "rb")) read and write bytes, while text mode (open(path, "r")) handles encoding automatically.

bytes objects support many of the same methods as strings — .split(), .strip(), .replace(), .find(), .startswith() — but operate on byte values rather than characters. The struct module packs and unpacks bytes to and from C-style data types, and the io.BytesIO class provides a file-like interface over in-memory bytes. Understanding the distinction between str (text) and bytes (binary data) is fundamental in Python 3, which enforces a strict separation that Python 2 did not.

Related terms: String, Immutable

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.