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.
Code
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
unicodedatamust 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
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Text ReverserReverse text by characters, words, or lines, counting Unicode code points so emoji stay intact.
FAQ
- Are there third-party dependencies?
- `unicodedata` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.