Sub topic 2
From characters to bytes: code points and UTF-8
This chapter assumes you can read basic Python, know what a byte is, and understand Big-O notation. It covers how a "character" becomes the bytes that sit in memory or on disk.
Characters, code points, and bytes
A string looks like a sequence of characters, but a computer stores only numbers. Three layers connect the two ideas:
- A character is the unit a person sees, such as
coré. - A code point is the number Unicode assigns to a character. It is written
U+0063forcandU+00E9foré. - An encoding is a rule that turns code points into bytes. UTF-8, UTF-16, and UTF-32 are three such rules.
Unicode defines the code points. The encoding decides how many bytes each one needs. Mixing up these layers causes most text bugs.
UTF-8 in practice
UTF-8 is a variable-width encoding. Each code point takes 1 to 4 bytes, depending on its value.
| Code point range | Bytes | Example |
|---|---|---|
| U+0000 to U+007F | 1 | `a` |
| U+0080 to U+07FF | 2 | `é` |
| U+0800 to U+FFFF | 3 | `€` |
| U+10000 to U+10FFFF | 4 | `😀` |
The first 128 code points match ASCII, so plain ASCII text is already valid UTF-8. The leading bits of each byte show its role, which is why a program can find character boundaries without reading from the start of the file.
Counting code points versus bytes
The same text has different lengths depending on what you count.
s = "café"
print(len(s)) # 4 code points
print(len(s.encode("utf-8"))) # 5 bytes, because é takes 2 bytes in UTF-8
print([hex(ord(c)) for c in s]) # ['0x63', '0x61', '0x66', '0xe9']len(s) counts code points. Encoding to UTF-8 produces five bytes, because é (0xe9) needs two of them. The ord function returns the code point number for a single character.
You can see the bytes directly:
for ch in ["a", "é", "€", "😀"]:
data = ch.encode("utf-8")
print(ch, len(data), data.hex(" "))This prints the byte counts 1, 2, 3, and 4, matching the table above.
How UTF-8 marks its bytes
Each byte tells you where it sits in a code point:
- A byte starting with
0is a complete one-byte character. - A byte starting with
110,1110, or11110begins a sequence of 2, 3, or 4 bytes. - A byte starting with
10is a continuation byte.
Continuation bytes always start with 10, so no continuation byte can be mistaken for the start of a character. If a program lands in the middle of a text, it can skip back to the nearest non-continuation byte. This property is called self-synchronization.
Why this matters for cost
Variable width changes what operations cost. If every code point took the same number of bytes, finding the character at position i would be a simple multiplication. In UTF-8 you cannot know where character i starts without scanning the bytes before it, so that lookup takes O(n) time. Languages respond differently. Python stores strings in a fixed width per string (1, 2, or 4 bytes per code point, chosen by the widest character) so that s[i] stays O(1). Rust and Go store UTF-8 and index by byte offset instead.
Common errors
- Using byte length as character count.
len(data)onbytesis not the number of characters. - Decoding with the wrong encoding. Bytes written as UTF-8 but read as Latin-1 produce garbled text such as
café. - Cutting bytes in the middle of a character. Slicing encoded bytes at an arbitrary offset can split a multi-byte sequence and make the result invalid.
data = "café".encode("utf-8")
try:
data[:4].decode("utf-8")
except UnicodeDecodeError:
print("sliced through the middle of é")Exercise
The string "naïve" has 5 code points. The character ï is U+00EF. How many bytes does it use in UTF-8, and why?
Show answer
6 bytes. The four ASCII letters n, a, v, and e take 1 byte each. The code point U+00EF falls in the range U+0080 to U+07FF, so it takes 2 bytes. The total is 4 + 2 = 6.
Exercise
You have a UTF-8 byte string and land on a byte whose bits are 10101001. Is this the start of a character? What should you do to find the start?
Show answer
No. A byte starting with 10 is a continuation byte. Move backward until you reach a byte that does not start with 10. That byte begins the character.