Bytes vs str
str is a sequence of Unicode characters. bytes is a sequence of integers in 0..255. You convert between them with an encoding such as UTF-8; you cannot concatenate them.
Detailed Explanation
Python 3 split text from binary on purpose. A username, a JSON body you intend to parse as text, and a log line are str. A JPEG, a protobuf payload, and a TLS record are bytes. Mixing them is a TypeError, which is better than the silent corruption Python 2 allowed.
A str is not stored as "one byte per character". It is Unicode. len("€") is 1. Encoding to UTF-8 produces b'\xe2\x82\xac', whose length is 3. len on str counts characters. len on bytes counts bytes. Those numbers match only for ASCII.
.encode(encoding="utf-8") turns str into bytes. .decode(encoding="utf-8") goes the other way. The encoding is a contract with the other end of the wire or the file. If you guess wrong you get UnicodeDecodeError, or worse, a string that looks almost right. UTF-8 is the default for the web and for most text files. Latin-1 is a 1:1 mapping from bytes to the first 256 code points and is sometimes used as an escape hatch, not as a guess for human language.
bytes literals are b"hello". Indexing a bytes object returns an int, not a one-byte bytes: b"abc"[0] == 97. Slicing returns bytes. bytearray is the mutable cousin.
I/O must pick a side. open(path, "r", encoding="utf-8") reads str. open(path, "rb") reads bytes. A socket's recv returns bytes. json.loads accepts str or UTF-8 bytes. Path.read_text and Path.read_bytes make the choice in the method name.
Do not decode binary formats as text. Do not encode text with a random encoding because a library wanted bytes. Pick UTF-8 unless a protocol names another encoding, and store the choice next to the data when it is not obvious.
Code Examples
text = "€10"
raw = text.encode("utf-8")
print(raw) # b'\xe2\x82\xac10'
print(len(text), len(raw)) # 3 5
print(raw.decode("utf-8")) # €10
# print(text + raw) # TypeError: can only concatenate str (not "bytes")data = b"abc"
print(data[0], data[0:1]) # 97 b'a' <- index is int, slice is bytes
print(list(data)) # [97, 98, 99]# Files: pick text or binary explicitly.
from pathlib import Path
path = Path("note.txt")
path.write_text("café", encoding="utf-8")
print(path.read_bytes()) # b'caf\xc3\xa9'
print(path.read_text(encoding="utf-8"))Common Gotchas
`b"abc"[0]` is `97`, not `b"a"`
use a slice when you need a `bytes` object of length 1.
Decoding with the wrong encoding can succeed and lie
`b"\xe2\x82\xac".decode("latin-1")` returns three characters, not `€`. Prefer UTF-8 and fail on errors with `errors="strict"`.
Windows text mode changes newlines
`"r"` translates `\\r\\n`. Use `"rb"` when the file is not actually text.
`str` and `bytes` both support `in`, slicing, and `find`
the APIs look similar on purpose. The types still do not mix.