Sub topic 5
Compatibility forms: NFKC and NFKD
This chapter assumes you know basic Python string handling. It also assumes you have met NFC and NFD from the previous chapter, where canonical normalisation made "caf\u00e9" and "cafe\u0301" compare equal. Here you will learn what the two "K" forms do beyond that, when they help, and which information they destroy.
Two kinds of equivalence
Unicode defines two relations between strings that look alike.
- Canonical equivalence means two sequences are the same character with the same appearance and meaning. A precomposed
éandeplus a combining acute accent are canonically equivalent. NFC and NFD only ever swap between such sequences. - Compatibility equivalence is weaker. Two sequences represent the same abstract character, but they differ in appearance or formatting. The ligature
fi(U+FB01) is compatible with the two lettersfi. A full-widthA(U+FF21) is compatible with a plainA. The circled digit①(U+2460) is compatible with1.
Compatibility characters exist mostly so that Unicode could round-trip older encodings that had their own ligature, full-width, or circled-digit code points. They are still in the standard, so they still show up in scraped web pages, PDFs, and text typed with East Asian input methods.
Canonical equivalence is always safe to apply. Compatibility equivalence is a lossy choice: you discard a distinction that someone made on purpose.
The four forms
Each normalisation form is a combination of two choices: which decomposition to use, and whether to recompose afterwards.
| Form | Decomposition | Recompose? | Typical use |
|---|---|---|---|
| NFD | Canonical | No | Inspect or strip combining marks |
| NFC | Canonical | Yes | Storage and exchange, the safe default |
| NFKD | Compatibility | No | Aggressive matching, then strip marks |
| NFKC | Compatibility | Yes | Search keys, deduplication, identifiers |
Every K form also applies all the canonical mappings. NFKC output is therefore always canonically normalised too, and you do not need to run NFC afterwards.
What NFKC changes
The next snippet shows the typical effects. NFKC folds ligatures, full-width letters, and circled digits into plain characters, while NFC leaves them alone.
import unicodedata
print(unicodedata.normalize("NFKC", "\ufb01")) # fi
print(unicodedata.normalize("NFKC", "\uff21\uff22\uff23")) # ABC
print(unicodedata.normalize("NFKC", "\u2460")) # 1
print(unicodedata.normalize("NFC", "\ufb01")) # the ligature is unchangedThe set of changes is wider than those three. The loop below runs several more through NFKC. It prints each result with ascii() so that non-ASCII outputs stay visible as escapes.
import unicodedata
samples = [
("superscript two", "x\u00b2"),
("trademark sign", "Kiro\u2122"),
("ellipsis", "wait\u2026"),
("no-break space", "a\u00a0b"),
("roman numeral nine", "\u2168"),
("fraction one half", "\u00bd"),
("half-width katakana", "\uff76"),
]
for name, text in samples:
out = unicodedata.normalize("NFKC", text)
print(name + ":", ascii(out))
# superscript two: 'x2'
# trademark sign: 'KiroTM'
# ellipsis: 'wait...'
# no-break space: 'a b'
# roman numeral nine: 'IX'
# fraction one half: '1\u20442'
# half-width katakana: '\u30ab'Notice three things in this output.
- The no-break space becomes an ordinary space. NFKC therefore removes one common source of "invisible" mismatches, but it does not touch every kind of whitespace. Other chapters cover whitespace cleanup in general.
- The fraction
½becomes1, then U+2044 (FRACTION SLASH), then2. The slash is not the ASCII/. If you want1/2, you need a follow-up replacement. - Half-width katakana
カbecomes the standard-widthカ. This is exactly the kind of variation you want gone before matching Japanese text.
NFKC versus NFKD
NFKD stops after decomposing. The difference matters only when the input has characters that can recompose. This example uses an accented é followed by the fi ligature, and prints the code points after each form.
import unicodedata
s = "\u00e9\ufb01" # e with acute, then the fi ligature
for form in ("NFC", "NFD", "NFKC", "NFKD"):
out = unicodedata.normalize(form, s)
codes = [f"U+{ord(c):04X}" for c in out]
print(form, len(out), codes)
# NFC 2 ['U+00E9', 'U+FB01']
# NFD 3 ['U+0065', 'U+0301', 'U+FB01']
# NFKC 3 ['U+00E9', 'U+0066', 'U+0069']
# NFKD 4 ['U+0065', 'U+0301', 'U+0066', 'U+0069']NFKC gives the shortest string with the accent kept as one code point. NFKD gives the longest, with the base letter and the accent separated. Choose NFKD when your next step is to filter out combining marks, as in accent stripping. Choose NFKC when the normalised string is the final form you will store or compare.
Some characters change even under NFC, because they are canonical singletons. The ohm sign U+2126 and the angstrom sign U+212B exist only for legacy reasons, and Unicode maps them canonically to the Greek capital omega and Å.
import unicodedata
print(unicodedata.normalize("NFC", "\u2126") == "\u03a9") # True
print(unicodedata.normalize("NFC", "\u212b") == "\u00c5") # TrueSo not every "look-alike" cleanup needs the K forms. Canonical equivalence covers these.
What you lose
NFKC is lossy and not reversible. Each mapping throws away a distinction, and in some tasks that distinction is the signal.
| Input | NFKC result | What is lost |
|---|---|---|
| `x²` | `x2` | Exponent becomes a different number or identifier |
| `H₂O` | `H2O` | Subscript, so formula structure is flattened |
| `™` | `TM` | A symbol becomes two letters that may read as a word |
| `fi` | `fi` | Nothing meaningful, a safe change |
| `A` | `A` | Nothing meaningful for most tasks |
| `①` | `1` | List marker becomes a bare digit |
The first three rows are the usual trouble. x² and x2 are different things in mathematics or code. Normalising "10²" to "102" can corrupt a number. If your text contains units, formulas, footnote markers, or list numbering, test NFKC on a sample of real data before putting it in a pipeline.
NFKC also does not do what people sometimes expect:
- It does not change case.
AbecomesA, nota. - It does not unify look-alikes from different scripts. A Cyrillic
а(U+0430) and a Latinaremain different, and NFKC will not help with spoofing or homoglyph attacks. - It does not remove accents.
éstaysé. - It does not turn curly quotes into straight quotes. Typographic punctuation needs its own mapping.
Combining NFKC with case folding
Caseless matching needs both steps, and the order matters because each step can break the other's guarantee. Case folding can produce text that is no longer normalised. The Greek letter ΐ (U+0390) folds to three code points.
import unicodedata
s = "\u0390"
folded = s.casefold()
print(len(s), len(folded)) # 1 3
print(unicodedata.is_normalized("NFC", folded)) # False
print(len(unicodedata.normalize("NFC", folded))) # 1The folded string is correct for comparison, but it is in decomposed form. If you compare it with another string that was folded and then left in a different form, the two can disagree. The standard fix is to normalise again after folding.
import unicodedata
def match_key(text):
text = unicodedata.normalize("NFKC", text)
text = text.casefold()
return unicodedata.normalize("NFKC", text)
pairs = [
("Stra\u00dfe", "STRASSE"),
("\ufb01eld", "FIELD"),
("\uff28\uff45\uff4c\uff4c\uff4f", "hello"),
]
for a, b in pairs:
print(match_key(a) == match_key(b)) # True, True, TrueThe first normalisation step matters because case folding works on code points. A full-width H has its own fold mapping, but NFKC first brings fi and similar compatibility characters to plain letters so that folding sees the ordinary alphabet. The second step restores a consistent normalised form after folding. Applying NFKC before and after folding is a cheap, safe default.
The Python documentation describes a stricter recipe for compatibility caseless matching that applies NFKD, case fold, and NFKD again in a longer chain. For most NLP pipelines, the two-NFKC version above gives the same practical result and is easier to read. If you work with unusual scripts, test your own data against both.
Where NFKC already runs in the wild
You may be using NFKC without knowing it.
- Python normalises identifiers with NFKC when it parses source code, so a variable written with a full-width letter is the same variable as its ASCII spelling.
- Some tokenisers, such as SentencePiece with its default
nmt_nfkcrule, apply an NFKC-based normalisation before splitting text. If you feed such a model text you have already normalised differently, results can shift in small ways. - Search engines commonly index NFKC-folded forms so that a query typed with half-width or full-width characters still finds the plain text.
Check the documentation of a model's tokeniser before you pre-normalise. Running NFKC on text that a tokeniser will normalise anyway is usually harmless. Running it on text for a model trained on raw, un-normalised input can change how it behaves.
Choosing a form
Use these criteria.
- Storing or exchanging text, with no wish to change meaning: NFC.
- Building a key for search, deduplication, or joins across messy sources: NFKC, followed by case folding and a second NFKC.
- Removing accents: NFKD or NFD, filter combining marks, then recompose. The NFKD variant also folds ligatures and full-width forms in the same pass.
- Tasks where compatibility characters carry meaning, such as scientific text, mathematics, or legal documents with footnote markers: stay with NFC, or apply a narrow custom mapping for only the characters you want to change.
The following helper does that audit.
import unicodedata
from collections import Counter
def nfkc_changes(texts):
changed = Counter()
for text in texts:
for ch in text:
out = unicodedata.normalize("NFKC", ch)
if out != ch:
changed[ch] += 1
return changed
corpus = ["Caf\u00e9 \u2460", "x\u00b2 + y\u00b2", "\uff28\uff49 \u2122"]
for ch, n in nfkc_changes(corpus).most_common():
print(f"U+{ord(ch):04X}", unicodedata.name(ch), n)The helper normalises one character at a time, which is enough for compatibility mappings that replace a single code point. Run on your own corpus, the report tells you exactly which characters NFKC would rewrite and how often.
Exercise
Predict the result of this code, and say which step handles which change: unicodedata.normalize("NFKC", "\uff28\uff25\uff2c\uff2c\uff2f\u00a0\uff37\uff4f\uff52\uff4c\uff44\u2460").casefold(). The input is full-width HELLO, a no-break space, full-width World, and a circled one.
Show answer
The result is hello world1. NFKC turns the full-width letters into ASCII HELLO and World, the no-break space into an ordinary space, and ① into 1, giving HELLO World1. casefold() then lowercases the string. NFKC alone does not change case, so the final step is needed.
Exercise
A chemistry corpus contains H₂O and CO₂. You normalise with NFKC before matching. What goes wrong, and what would you do instead?
Show answer
NFKC maps the subscript digits to ordinary digits, so H₂O becomes H2O and CO₂ becomes CO2. The subscript formatting that marks the formula structure is lost, and the result can collide with unrelated tokens. Use NFC for the main text, or apply a custom mapping that leaves subscripts alone. If you still need a matching key, store it separately and keep the original text.