Lesson · Strings & Text
Unicode, Encoding & Bytes
48 min readUnicode, Encoding & Bytes
Text and binary data are different types for a reason. Encoding converts Unicode text to bytes, decoding reverses the operation, and explicit boundaries prevent mojibake and data corruption.
Learning goals
- Explain what a code point is and how a
strdiffers from thebytesthat store it. - Encode text to UTF-8 and decode it back, and predict where
lenof the text and the bytes diverge. - Edit a
bytearrayin place, take an immutable copy withbytes(), and say why the same edit fails onbytes. - Read a
UnicodeDecodeErrororUnicodeEncodeErrorand decide when an expliciterrors=policy is acceptable. - Say why binary data must not be decoded merely because the bytes look like text.
Mental model
A str and its encoded bytes are different objects holding different information: the text holds code points, the encoded form holds the byte sequence a system actually stores. Every crossing needs a codec, and the codec plus its error policy decides whether a mismatch fails loudly or turns into silent mojibake. The type in hand also decides what is possible: bytes cannot be edited, while bytearray exists for exactly that.
Text holds code points, bytes hold storage
every crossing needs a codec
Mental model
the same mechanism as a compact list
"café ☕" text: str, a sequence of Unicode code points
↓ encode("utf-8") text → bytes at the storage/network boundary
data bytes: immutable, indexed as integers 0..255
↓ decode("utf-8") bytes → text, the reverse crossing
bytearray(data) same byte values with in-place editing allowedCore idea
Text and bytes are separate types on purpose: a str holds Unicode code points, and encoding such as UTF-8 converts them into the byte sequence that files, sockets, and environment variables actually carry. Decoding reverses the trip, and because every conversion names a codec and an error policy, failures like UnicodeDecodeError pinpoint exactly where two sides of a boundary disagreed. bytes is immutable while bytearray provides the same byte values with in-place edits.
Unicode code points
Python text is Unicode. A Unicode code point is an abstract number assigned to a character-like unit, but user-perceived characters can consist of multiple code points.
str vs bytes
This comparison separates str from bytes in the context of Unicode, Encoding & Bytes. Focus on ownership, mutability, cost, failure behavior, and API intent rather than treating the two choices as interchangeable.
Encoding
Encoding converts text into bytes according to a named codec such as UTF-8. The encoding must match the expectations of the external system or file format.
Decoding
Decoding interprets bytes according to a codec and produces text. Decoding with the wrong codec can fail or produce corrupted-looking text.
UTF-8
UTF-8 is a variable-length Unicode encoding and is the default choice for much modern interchange. ASCII bytes keep the same values in UTF-8.
Encoding errors
Encoding or decoding can fail when a character cannot be represented or byte sequences are invalid. Choose an explicit error policy only when replacement or skipping is truly acceptable.
bytearray
bytearray is the mutable counterpart of bytes: a sequence of integers from 0 to 255 whose elements can be reassigned, appended, or removed in place. Indexing yields an int, slicing yields another bytearray, and bytes(buffer) takes an immutable copy when a fixed value is needed. Like bytes it carries no text meaning until decoded with an explicit codec.
Binary data
Binary data is modeled with bytes, bytearray, memory views, streams, and structured parsers. Do not decode arbitrary binary formats just because some bytes happen to map to text.
Walkthrough
text.encode("utf-8")converts the code points to bytes, soprint(data)showsb'caf\xc3\xa9 \xe2\x98\x95', wherecand the space stay one byte each and each non-ASCII character takes several.data.decode("utf-8")reverses the crossing and prints the original text, which is the round trip that proves the codec pair matches in both directions.bytearray(data)holds the same byte values in a mutable container:buffer[0] = ord("C")swaps the first byte, andbytes(buffer).decode("utf-8")printsCafé ☕; the same assignment ondatawould raiseTypeError.- Predict before running: which characters in
café ☕survive as single bytes in the literal, and why editing index0cannot corrupt the text.
Experiments to try
- Print
len("café ☕")andlen("café ☕".encode("utf-8")); count the multi-byte characters and explain the difference between code points and bytes. - Encode
"café"as UTF-8 and decode it as"latin-1"; the result is mojibake rather than an error, which shows that a wrong codec can fail quietly. - Run
text.encode("ascii")and read theUnicodeEncodeError; then run it witherrors="replace"and inspect what the?substitution discards. - Try decoding a truncated sequence such as
b"\xc3"and check which side of the boundary reports theUnicodeDecodeError.
Common mistakes
- Decoding arbitrary binary data: UTF-8 accepts many byte sequences, so a decode can succeed on bytes that were never text and produce mojibake that surfaces far from the cause; only decode when the format defines text.
- Leaving the codec to the environment:
open()withoutencoding=follows the platform default, so the same file can read differently across machines; passencoding="utf-8"explicitly at every boundary. - Silencing conversion with a blanket
errors="ignore": characters and bytes then vanish without a trace, while the default policy raises where the mismatch is; useerrors=only when replacement is genuinely acceptable. - Assuming
lencounts characters a reader sees: one emoji or composed accent can span several code points, so length and slice math can split a visible character.
Practice: Easy
- Encode
"café ☕"to UTF-8, decode it back, and label the three types in the round trip:str, thenbytes, thenstragain. - Print
b"abc"[0]and"abc"[0]; state the type each indexing operation returns and why they differ. - Encode
"café"as UTF-8 and decode those bytes as"latin-1"; record the mojibake output and explain why no exception interrupted the wrong codec.
Practice: Medium
- Compare
len("café ☕")withlen("café ☕".encode()); list the byte cost of each character and explain where the extra length comes from. - Round-trip
"Straße ☕"through UTF-8 with an equality assertion, then repeat with"ascii"and describe exactly where it fails. - Patch one byte of
bytearray(b"cat")to getb"cut", then attempt the same edit on abytesobject and read theTypeError; state what the mutability difference is for.
Practice: Hard
- Design a small text-file helper that always passes
encoding="utf-8", defines what happens when a character cannot be encoded, and reports what was written; define one test before implementing. - Build a failure lab with three cases: a truncated byte sequence decoded as UTF-8, an
"ascii"encode of non-ASCII text, and a wrong-codec decode that produces mojibake; explain which failures are loud and which are quiet. - Connect this lesson to files and protocols: explain why every boundary needs both a codec and an error policy, and describe a realistic incident caused by two sides choosing different encodings.
Lesson checklist
- I can say what exists on each side of the text/bytes boundary and which type is on which side.
- I can encode and decode with a named codec and predict where lengths diverge.
- I can explain
bytesimmutability againstbytearrayin-place edits with a concrete example. - I can name the loud conversion failure and the quiet mojibake failure and say when
errors=is justified.
Remember
Text and bytes are different types for a reason: a `str` holds Unicode code points, an encoding converts them to the byte sequence systems store, and decoding reverses the crossing with an explicit codec and error policy. UTF-8 covers the full range with variable-length bytes, `bytes` stays immutable while `bytearray` permits in-place edits, and the policy at each boundary decides whether a mismatch fails loudly or becomes silent mojibake.
Interview angles
What is the main purpose of **Unicode code points**?+
Python text is Unicode. A Unicode code point is an abstract number assigned to a character-like unit, but user-perceived characters can consist of multiple code points.
What should you pay attention to when using **str vs bytes**?+
This comparison separates str from bytes in the context of Unicode, Encoding & Bytes. Focus on ownership, mutability, cost, failure behavior, and API intent rather than treating the two choices as interchangeable.
How does **Encoding** fit into this lesson?+
Encoding converts text into bytes according to a named codec such as UTF-8. The encoding must match the expectations of the external system or file format.
Why can decoding binary data with UTF-8 appear to work?+
UTF-8 accepts a large share of possible byte sequences, so a decode can succeed and return plausible-looking text for bytes that were never text. Success proves nothing about intent; decode only when the format defines the bytes as text, and keep binary formats in bytes.