Sub topic 4
Unicode normalisation: NFC and NFD
This chapter assumes you know basic Python (strings, functions, list comprehensions). It also assumes you know that text is stored as bytes in an encoding such as UTF-8, and that you have read the earlier chapters on code points and case folding. By the end you should be able to explain why two identical-looking strings compare as unequal. You should also be able to pick between NFC and NFD, and place normalisation correctly in a pipeline.
Why identical-looking strings differ
Unicode often offers more than one way to write the same visible character. The letter "é" can be one code point, U+00E9 (LATIN SMALL LETTER E WITH ACUTE). It can also be two code points: U+0065 (the letter e) followed by U+0301 (COMBINING ACUTE ACCENT). A renderer draws both the same way. Python compares code points, so it treats them as different strings.
import unicodedata
a = "caf\u00e9" # e with acute 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(a.encode("utf-8")) # b'caf\xc3\xa9'
print(b.encode("utf-8")) # b'cafe\xcc\x81'
print(unicodedata.normalize("NFC", b) == a) # True
print(unicodedata.normalize("NFD", a) == b) # TrueThe two strings differ at every level: as code points, in length, and as UTF-8 bytes. Anything keyed on exact string equality will treat them as different words. That includes dictionary lookups, vocabulary tables, set membership, database joins, and deduplication.
Both strings are legal, and both can occur in real data. Text typed on one keyboard may arrive precomposed, text copied from another system may arrive decomposed, and some file systems and PDF extractors produce decomposed forms. You cannot see the difference, so you have to normalise on purpose.
Canonical equivalence
Unicode defines two kinds of equivalence between sequences.
- Canonical equivalence means two sequences represent the same abstract character and should look and behave identically.
U+00E9andU+0065 U+0301are canonically equivalent. - Compatibility equivalence is weaker. The sequences represent the same character but may differ in appearance or meaning, such as the ligature "fi" and the letters "fi". The next chapter covers it.
NFC and NFD only apply canonical equivalence. They never change what a character means. They only choose which of several equivalent spellings to use.
The two canonical forms
- NFD (Normalization Form D, "decomposed") splits every character into its base character plus combining marks, as far as the Unicode data allows.
- NFC (Normalization Form C, "composed") first decomposes, then recombines marks with their base characters into precomposed code points wherever one exists.
Python exposes both forms through unicodedata.normalize(form, text). The function returns a new string and never changes its input.
import unicodedata
def show(s):
return " ".join(f"U+{ord(c):04X}" for c in s)
print(show("\u00e9")) # U+00E9
print(show(unicodedata.normalize("NFD", "\u00e9"))) # U+0065 U+0301
print(show(unicodedata.normalize("NFC", "e\u0301"))) # U+00E9
print(unicodedata.name("\u0301")) # COMBINING ACUTE ACCENT
print(unicodedata.combining("\u0301")) # 230unicodedata.combining() returns the canonical combining class of a character. It returns 0 for ordinary characters and a non-zero number for marks that attach to a previous character. You will use this to find accents in the next chapter.
Which one should you choose?
Most pipelines should pick one form and use it everywhere. The two forms have different strengths.
| Question | NFC | NFD |
|---|---|---|
| Typical string length | Shorter, one code point per accented letter where possible | Longer, base letter plus marks |
| Match with most real-world text | Best; web content, keyboards and most software emit NFC | Less common as input |
| Easy to strip accents | No, marks are fused into letters | Yes, marks are separate code points |
| Easy to treat marks separately | No | Yes |
| Typical use | Storage, comparison, default for text interchange | Intermediate step for accent handling, some linguistic analysis |
A practical rule: store and compare in NFC. Switch to NFD temporarily only when you need to work on the marks themselves. NFC is also what the W3C recommends for web content, and it keeps strings shorter than NFD does.
What normalisation does beyond composing and splitting
Singletons
Some characters exist in Unicode only for historical reasons and map to one other character. The ANGSTROM SIGN U+212B and the OHM SIGN U+2126 are examples. NFC and NFD both replace them with the ordinary letters they duplicate.
import unicodedata
print(hex(ord(unicodedata.normalize("NFC", "\u212b")))) # 0xc5 (LATIN CAPITAL LETTER A WITH RING ABOVE)
print(hex(ord(unicodedata.normalize("NFC", "\u2126")))) # 0x3a9 (GREEK CAPITAL LETTER OMEGA)This is a one-way change. After NFC you can no longer tell that the original used the angstrom sign. That is almost always what you want.
Canonical ordering of marks
A letter can carry several combining marks. The order in which they are stored may differ even when the visual result is the same. NFD sorts adjacent marks by their combining class so that equivalent sequences end up identical.
import unicodedata
x = "q\u0307\u0323" # q, dot above, dot below
y = "q\u0323\u0307" # q, dot below, dot above
print(x == y) # False
print(unicodedata.normalize("NFD", x) == y) # True
print(unicodedata.normalize("NFC", x) ==
unicodedata.normalize("NFC", y)) # TrueNeither string has a precomposed form, so NFC leaves the marks as separate code points. NFC still puts them in the canonical order, which is why the last comparison is True. This is a reason to call normalize even on text you expect to have no precomposed characters.
Hangul syllables
Korean syllable blocks have an algorithmic decomposition into conjoining letters (jamo). NFD splits them and NFC joins them back.
import unicodedata
syllable = "\uac01"
decomposed = unicodedata.normalize("NFD", syllable)
print(len(syllable), len(decomposed)) # 1 3
print([f"{ord(c):04X}" for c in decomposed]) # ['1100', '1161', '11A8']
print(unicodedata.normalize("NFC", decomposed) == syllable) # TrueNot every accented letter has a precomposed form
NFC is not a promise of one code point per visible character. Many letter and mark combinations, especially in African languages, transliteration schemes and mathematical notation, have no precomposed code point. They stay as base plus mark even in NFC. A "character" the reader sees can therefore still span several code points. Counting user-perceived characters (grapheme clusters) needs a library that implements Unicode text segmentation, because len() counts code points.
Properties you can rely on
- Idempotent. Normalising twice gives the same result as normalising once.
- Safe on ASCII. Pure ASCII text is unchanged by every form.
- Length may change. Never assume
len(text)is the same before and after. Character offsets computed before normalisation (for example, entity spans) no longer line up afterwards. - Not reversible. After NFC you cannot recover whether the input was composed or decomposed.
You can check whether a string is already normalised without building a new one:
import unicodedata
print(unicodedata.is_normalized("NFC", "caf\u00e9")) # True
print(unicodedata.is_normalized("NFC", "cafe\u0301")) # Falseunicodedata.is_normalized is available from Python 3.8.
What normalisation does not fix
NFC and NFD handle only canonical equivalence. Three common surprises remain.
- Lookalike letters from different scripts. Cyrillic "а" (
U+0430) and Latin "a" (U+0061) are different letters. No normalisation form merges them. - Compatibility characters. Ligatures, full-width letters and circled digits stay unchanged under NFC. Use NFKC for these (next chapter).
- Case differences.
"É"and"é"stay different. Case folding is a separate step.
import unicodedata
print("\u0430" == "a") # False
print(unicodedata.normalize("NFC", "\u0430") == "a") # False
print(unicodedata.normalize("NFC", "\ufb01") == "fi") # False
print(unicodedata.normalize("NFC", "\u00c9") == "\u00e9") # FalseWhere normalisation belongs in code
Normalise once, at the boundary where text enters your system, and also normalise anything you compare against. A vocabulary file, a gazetteer, a stop word list or a set of user-provided search terms must be in the same form as the text. If the list is composed and the text is decomposed, entries will silently fail to match.
import unicodedata
def nfc(text):
return unicodedata.normalize("NFC", text)
index = {nfc("caf\u00e9"): "coffee shop"}
query = "cafe\u0301"
print(index.get(query)) # None
print(index.get(nfc(query))) # coffee shopThe failed lookup does not raise an error. It looks like a missing key, which makes this a hard bug to notice.
Normalise before tokenising
Many tokenisers split on character classes. In Python's re, \w matches letters, digits and underscore, but a bare combining mark is not alphanumeric. A decomposed word can therefore lose its accent or be cut apart.
import re
import unicodedata
decomposed = "cafe\u0301"
print(re.findall(r"\w+", decomposed))
# ['cafe'] the accent is dropped because U+0301 is not matched by \w
composed = unicodedata.normalize("NFC", decomposed)
print(re.findall(r"\w+", composed))
# ['caf\u00e9'] the whole word is keptHere the tokeniser throws away the accent without any warning. Normalising to NFC first fixes this for every letter that has a precomposed form. For letters that stay decomposed in NFC, a regular expression based on \w can still cut off the mark, so test your tokeniser on your own data. The third-party regex module offers \p{M} to match marks explicitly.
Normalise before case folding, and again after
Case folding can create new compositions or decompositions, so the safest sequence for caseless matching is normalise, fold, normalise:
import unicodedata
def match_key(text):
text = unicodedata.normalize("NFD", text)
text = text.casefold()
return unicodedata.normalize("NFD", text)
print(match_key("\u00c9COLE") == match_key("e\u0301cole")) # TrueThis pattern follows the Unicode standard's definition of caseless matching, which applies NFD before and after folding. The second pass is cheap and removes edge cases. In many pipelines a single NFC pass followed by casefold() is enough, but the double pass is the one the standard defines.
Common errors
- Normalising only one side of a comparison. Always apply the same form to both strings.
- Choosing NFD for storage and NFC for lookup (or the reverse). Pick one form per data store and document it.
- Running tokenisation first. As shown above, this can lose marks.
- Assuming
len()equals the visible character count. It counts code points, in either form. - Mixing up bytes and strings.
unicodedata.normalizeaccepts onlystr. Decode bytes with the right encoding first (see the encodings chapter). - Normalising too late. If you have already stored offsets, hashes, or IDs computed from raw text, normalising later changes them.
Exercise
A search index stores the word "résumé" as entered by editors (precomposed). A user pastes "re\u0301sume\u0301" (decomposed) into the search box and gets no results, although the page shows the same word. Explain the cause and give a minimal fix in Python.
Show answer
The two strings contain different code points (U+00E9 versus e plus U+0301), so string equality and hashing treat them as different keys. Normalise both the indexed terms and the query to the same form, for example unicodedata.normalize("NFC", query), before lookup. The index must be built with the same normalisation, otherwise the fix only works one way.
Exercise
After s = unicodedata.normalize("NFC", text), a colleague claims that len(s) now equals the number of letters a human would count. Give a reason this can be false.
Show answer
NFC only composes where Unicode defines a precomposed code point. Some letter and mark combinations have none, so they remain as a base character plus a combining mark, and len() counts each code point. Counting user-perceived characters requires grapheme cluster segmentation, which len() does not do.
Exercise
Write a function same_text(a, b) that returns True when two strings are canonically equivalent, and show that it returns True for "caf\u00e9" and "cafe\u0301" but False for "caf\u00e9" and "CAF\u00c9".
Show answer
import unicodedata
def sametext(a, b):
return unicodedata.normalize("NFC", a) == unicodedata.normalize("NFC", b)
print(sametext("caf\u00e9", "cafe\u0301")) # True
print(same_text("caf\u00e9", "CAF\u00c9")) # False
Canonical normalisation does not change case, so the second comparison stays False. Add casefold() to both sides for caseless matching.