unicodedata Strips Accents With NFD

unicodedata.normalize with NFD splits accented letters into base plus combining marks; dropping category Mn code points turns Zoë into Zoe for search keys.

PythonData Integrity

Code

pythonsnippet
17 lines
import unicodedata

def strip_accents(text: str) -> str:
    # NFD 分解:把带变音的字母拆成基字符 + 组合字符
    decomposed = unicodedata.normalize("NFD", text)
    # 类别 Mn(非间距组合记号)的码点直接丢弃
    return "".join(c for c in decomposed if unicodedata.category(c) != "Mn")

names = ["Zoë", "José", "Ångström", "naïve café", "北京"]
for name in names:
    print(f"{name} -> {strip_accents(name)}")

# NFC 把组合序列组合成单码点:NFC(decomposed) 与字面 é 的码点序列一致(归一化前是 5 vs 4 两个不同序列)
decomposed = "cafe" + chr(0x301)
print("decomposed length:", len(decomposed))
print("NFC composes back:", unicodedata.normalize("NFC", decomposed) == "café")
print("lengths:", len("café"), len(decomposed))

How it works

Count the function strip_accents as the entire surface area of unicodedata Strips Accents With NFD.

Repetition is confined to for name in names — the rest of the file is straight-line.

What to watch for

  • unicodedata must be installed first — the snippet imports it directly.

Applying it

The primary signature is def strip_accents(text: str) -> str

The demo output is labeled (decomposed length:, NFC composes back:, lengths:), so every printed line maps back to its originating operation.

Import strip_accents from the file and call it — the rest of the code is implementation detail.

Statements that matter

def strip_accents(text: str) -> str:
    # NFD 分解:把带变音的字母拆成基字符 + 组合字符
    decomposed = unicodedata.normalize("NFD", text)
    # 类别 Mn(非间距组合记号)的码点直接丢弃
    return "".join(c for c in decomposed if unicodedata.category(c) != "Mn")

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`unicodedata` — install it with the package manager before running.