What is the difference between `str` and `bytes` in Python 3, and when do you need to `.encode()` or `.decode()`?
Answer
`str` holds a sequence of Unicode code points — abstract text with no fixed byte representation — while `bytes` holds a sequence of raw 8-bit values, which is what files, sockets and most external systems actually transmit. `.encode("utf-8")` converts a `str` into `bytes` using a chosen encoding, and `.decode("utf-8")` converts `bytes` back into a `str`, interpreting the raw bytes according to that same encoding. A `str`/`bytes` conversion is needed specifically where text crosses a text/binary boundary — for example, handing a string to a socket or interpreting raw bytes as text; binary files and sockets themselves operate purely on `bytes` with no implicit encoding applied at all, while Python's *text-mode* file wrappers (`open(path)` without `"b"`) perform that encode/decode step for you automatically, using a platform-dependent default encoding unless you specify one, which can silently be wrong for legacy data.
Strong answer includes
- str is abstract Unicode text, bytes is raw 8-bit data
- encode converts str to bytes, decode converts bytes to str
- binary files/sockets carry raw bytes with no implicit encoding; text-mode file wrappers do the encode/decode step
Practical example
"café".encode("utf-8")produces `b'caf\xc3\xa9'` because é takes two bytes in UTF-8; decoding those bytes with the wrong codec like `"latin-1"` silently produces garbled mojibake text instead of an error.