01 · Text, Unicode, and bytes¶
Start here · about 15 minutes
The letter A can be written three ways: A ↔ U+0041 ↔ 01000001. This notebook makes every arrow observable in Python, then tests examples where one displayed character takes more than one byte.
You will be able to: distinguish a code point from a byte; inspect UTF-8; explain why 256 byte values cover far more than 256 characters.
Use Shift+Enter to run a cell. Change the experiment inputs, then use Kernel → Restart Kernel and Run All Cells to check the whole story. Every unit runs independently. Markdown cells are editable too: double-click one to write down what you observe.
1 · One letter, three representations¶
ord() returns a code point as an integer. U+0041 writes that integer in hexadecimal. .encode("utf-8") produces a Python bytes object. Iterating over it gives integers, one per byte.
Predict: will the code point and byte value still match if you replace A with 猫?
Python: repr() shows a diagnostic representation. F-strings interpolate {expr}; :04X and :08b mean zero-padded hex/binary with minimum widths 4/8. [expr for x in iterable] is a list comprehension.
text = "A"
print("Text:", repr(text))
for character in text:
print("Code point:", f"U+{ord(character):04X}")
raw = text.encode("utf-8")
print("Python bytes:", raw)
print("Byte values:", list(raw))
print("Hex:", [f"{value:02X}" for value in raw])
print("Bits:", [f"{value:08b}" for value in raw])
assert raw.decode("utf-8") == text
Text: 'A' Code point: U+0041 Python bytes: b'A' Byte values: [65] Hex: ['41'] Bits: ['01000001']
2 · Count different representations¶
A byte takes 256 values, so its inclusive range is 0–255, not [0, 256]. Individual bits are 0 or 1.
Also distinguish a Unicode code point from a grapheme cluster: a unit perceived as one displayed character, which can contain several code points. Python len(str) counts code points. The installed regex library can count grapheme clusters with \X.
Predict: will é and e followed by a combining accent have the same counts?
Python: Raw strings (r"...") preserve backslashes. In f-strings, !r applies repr() and >N right-aligns. range(256) excludes its stop value, 256.
import regex
samples = ["A", "猫", "🙂", "é", "é", "👩💻"]
print(f'{"text":14} {"graphemes":>10} {"code points":>12} {"UTF-8 bytes":>12}')
for text in samples:
print(f'{text!r:14} {len(regex.findall(r"\X", text)):>10} {len(text):>12} {len(text.encode("utf-8")):>12}')
print("Smallest byte:", min(bytes(range(256))))
print("Largest byte:", max(bytes(range(256))))
text graphemes code points UTF-8 bytes 'A' 1 1 1 '猫' 1 1 3 '🙂' 1 1 4 'é' 1 1 2 'é' 1 2 3 '👩\u200d💻' 1 3 11 Smallest byte: 0 Largest byte: 255
3 · More than one byte can represent one code point¶
A byte vocabulary contains the possible pieces, not a separate entry for every complete character. UTF-8 combines those pieces into sequences of one to four bytes per Unicode scalar value.
Try: replace the text below with any short phrase, ideally in more than one script. Watch where the character boundaries and byte boundaries differ.
Python: all(condition for x in iterable) evaluates a generator, stopping at the first false result.
my_text = "A猫🙂"
for character in my_text:
print(repr(character), f"U+{ord(character):04X}", list(character.encode("utf-8")))
assert all(0 <= value <= 255 for value in my_text.encode("utf-8"))
assert my_text.encode("utf-8").decode("utf-8") == my_text
'A' U+0041 [65] '猫' U+732B [231, 140, 171] '🙂' U+1F642 [240, 159, 153, 130]
4 · A piece of valid UTF-8 need not be valid UTF-8¶
Predict: what happens if we decode just the first byte of 猫? This matters later because a tokenizer can split a character's bytes across tokens.
Python: raw[:n] selects the first n bytes. except UnicodeDecodeError handles that exception type.
raw = "猫".encode("utf-8")
for length in range(1, len(raw) + 1):
piece = raw[:length]
try:
print(list(piece), "→", piece.decode("utf-8"))
except UnicodeDecodeError:
print(list(piece), "→ incomplete UTF-8 sequence")
[231] → incomplete UTF-8 sequence [231, 140] → incomplete UTF-8 sequence [231, 140, 171] → 猫
5 · Similar appearance does not imply identical text¶
Normalizing text can change its code points and bytes. A tokenizer does not automatically normalize just because it uses UTF-8. Exact reconstruction and normalization are separate choices.
import unicodedata
first = "é"
second = "é"
print("Same string:", first == second)
print("First bytes:", list(first.encode("utf-8")))
print("Second bytes:", list(second.encode("utf-8")))
print("Equal after NFC normalization:", unicodedata.normalize("NFC", first) == unicodedata.normalize("NFC", second))
Same string: False First bytes: [195, 169] Second bytes: [101, 204, 129] Equal after NFC normalization: True
Your experiment¶
Edit candidate, predict all three counts before running, then check exact reconstruction. Empty text is also a useful input.
candidate = "Your own example: café 猫"
print("Graphemes:", len(regex.findall(r"\X", candidate)))
print("Code points:", len(candidate))
print("Bytes:", len(candidate.encode("utf-8")))
assert candidate.encode("utf-8").decode("utf-8") == candidate
Graphemes: 24 Code points: 24 Bytes: 27
What you found¶
- My example and prediction:
- What happened:
- My revised explanation of character / code point / byte:
- Why 256 byte values can represent multilingual text:
Toward the CS336 tokenizer: you now know how to inspect the input representation and check lossless conversion before thinking about BPE.
References: Python Unicode HOWTO, Python bytes.