Sub topic 2
Compatibility forms: NFKC and NFKD
This chapter assumes Python 3, the unicodedata module, and the NFC and NFD forms from the previous chapter. NFKC and NFKD go further than NFC and NFD. They also replace compatibility characters, such as ligatures, full-width letters, and circled digits, with plain equivalents. That replacement removes formatting, so use these forms only when the loss is acceptable.
import unicodedata
print(unicodedata.normalize("NFC", "\ufb01")) # ligature unchanged
print(unicodedata.normalize("NFKC", "\ufb01")) # fi
print(unicodedata.normalize("NFKC", "\uff21\uff22\uff23")) # ABC
print(unicodedata.normalize("NFKC", "\u2460")) # 1NFKC recomposes the result. NFKD decomposes it and leaves the parts separate, which helps when you want to filter out combining marks. For matching and search, NFKC is usually the right choice.
Removing accents and diacritics safely
Accent removal decomposes text with NFD, drops the combining marks, and recomposes the result. Letters such as "ø", "ł", and "ß" have no decomposition, so they survive unchanged.
import unicodedata
def strip_accents(text):
decomposed = unicodedata.normalize("NFD", text)
kept = "".join(ch for ch in decomposed if not unicodedata.combining(ch))
return unicodedata.normalize("NFC", kept)
print(strip_accents("café naïve")) # cafe naiveStripping accents can merge distinct words. In Swedish, "å" is a separate letter, and "resume" and "résumé" have different meanings in some contexts. Strip accents only when your task treats the accented and plain forms as the same.
Cleaning whitespace and punctuation
Use re.sub to collapse runs of whitespace, and str.translate to remove punctuation. Run NFKC first, because it converts the full-width space (U+3000) and the non-breaking space (U+00A0) into ordinary spaces.
import re
import string
def clean_whitespace(text):
return re.sub(r"\s+", " ", text).strip()
def strip_punctuation(text):
table = str.maketrans("", "", string.punctuation)
return text.translate(table)
raw = " Hello,\t\tworld! \n\nNice day... "
print(clean_whitespace(raw)) # Hello, world! Nice day...
print(strip_punctuation(clean_whitespace(raw))) # Hello world Nice daystring.punctuation covers only ASCII marks. Curly quotes and em dashes remain unless you add them to the table.
diagram mermaid caption: Cleaning pipeline order for compatibility, accents, and whitespace alt: A top-to-bottom flow starting at raw text, then NFKC, then accent stripping, then whitespace cleanup, ending at clean text.
flowchart TD
A[Raw text] --> B[NFKC normalise]
B --> C[Strip accents if needed]
C --> D[Collapse whitespace]
D --> E[Clean text]exercise Q: What does unicodedata.normalize("NFKC", "\u00b2") return, and why would this break a maths tutor app that stores "x²"? A: It returns "2". The exponent becomes a plain digit, so "x²" turns into "x2", which means a different expression.