Sub topic 10
Grapheme Clusters and Normalization: When Length Is Not Obvious
This chapter assumes you know that a Python str is a sequence of Unicode code points and that UTF-8 encodes each code point as 1 to 4 bytes. It also assumes you are comfortable with indexing and slicing. Here you will see why "one character per position" still fails for text that people read.
Three Ways to Count Text
A string has three different lengths, depending on what you count:
- Bytes are the units stored in memory after encoding.
- Code points are the numbered Unicode entries. Python's
lencounts these. - Grapheme clusters are what a reader sees as one character. The Unicode standard calls them "user-perceived characters".
Most plain English text has one code point per grapheme cluster, so the three counts only differ in the byte count. Accents, emoji, and many scripts break that pattern.
Combining Marks and Normalization
The letter "é" can be stored in two ways. It can be one precomposed code point, U+00E9. It can also be "e" followed by U+0301, a combining acute accent. Both render the same way, but they are different strings.
import unicodedata
a = "caf\u00e9" # é as one code point
b = "cafe\u0301" # e followed by a combining acute accent
print(a == b) # False
print(len(a), len(b)) # 4 5
print(unicodedata.normalize("NFC", b) == a) # TrueNormalization converts text to a canonical form so that equal-looking text compares equal. The four forms are:
| Form | What it does |
|---|---|
| NFD | Decomposes characters into base letter plus combining marks |
| NFC | Decomposes, then recomposes where a precomposed code point exists |
| NFKD | Like NFD, and also replaces compatibility variants such as "fi" with "fi" |
| NFKC | Like NFC, with the same compatibility replacements |
NFC is the usual choice for storing and comparing text. The K forms lose information, because "fi" becomes two letters, so use them for search keys rather than for stored data.
Normalization does not cover case. For caseless comparison, use casefold(), which handles cases like German "ß" becoming "ss", and normalize as well.
Grapheme Clusters Beyond Accents
Some characters need many code points even after normalization. An emoji family joins a man, a woman, and a girl with invisible zero-width joiner (ZWJ) code points. A flag is a pair of regional indicator letters. Python's standard library has no grapheme segmentation, but the third-party regex package (install it with pip install regex) supports \X, which matches one grapheme cluster.
import regex
family = "\U0001F468\u200d\U0001F469\u200d\U0001F467"
flag = "\U0001F1EF\U0001F1F5"
for s in (family, flag):
print(len(s), len(regex.findall(r"\X", s)), len(s.encode("utf-8")))
# 5 1 18
# 2 1 8The family is 5 code points, 1 grapheme cluster, and 18 bytes. The flag is 2 code points, 1 grapheme cluster, and 8 bytes. Grapheme counts also depend on the Unicode version, because new emoji sequences are added over time.
Where This Breaks Real Programs
These mistakes follow directly from the three lengths:
- Truncating by index.
s[:10]can cut between a base letter and its accent, or in the middle of an emoji sequence. The result renders as a stray mark or a broken symbol. - Reversing a string.
s[::-1]moves a combining mark in front of the wrong letter. - Enforcing length limits. A "20 character" username limit should say which unit it counts. Counting code points lets a user write a long string of stacked marks. Counting bytes penalizes non-Latin scripts.
- Comparing without normalizing. Two users who both typed "café" can end up as different keys.
Indexing stays cheap, because a Python string gives O(1) access to a code point. Grapheme segmentation is not O(1) per position. To find the 10th grapheme, you must scan from the start and apply the segmentation rules, which makes the lookup O(n).
Choosing a Unit
Pick the unit that matches the job:
- Use bytes for storage size, network limits, and file formats.
- Use code points for most programmatic processing, such as parsing, where the format defines its own delimiters.
- Use grapheme clusters for cursor movement, truncation shown to users, and display-width limits.
- Use normalized code points for equality, sorting keys, and deduplication.
Exercise
The string s = "n\u0303" is "n" followed by a combining tilde. What are len(s) and the result of len(unicodedata.normalize("NFC", s))? Why does the second number differ, and does either number match the count of visible characters?
Show answer
len(s) is 2, because the string holds two code points. After NFC the pair is composed into the single precomposed code point U+00F1 ("ñ"), so the length is 1. The NFC result matches the one visible character here only because Unicode defines a precomposed form for "ñ". For a combination with no precomposed form, NFC would keep several code points, so grapheme segmentation is the reliable way to count visible characters.