unicodedata.normalize Composes Lookalike Text

The same word can be one precomposed codepoint or a base letter plus a combining mark; unicodedata.normalize('NFC') makes both spellings compare equal.

PythonData Integrity

Code

pythonsnippet
15 lines
import unicodedata

composed = "café"  # é 是单个码点 U+00E9
decomposed = "cafe\u0301"  # e + 组合尖音符 U+0301

print("lengths :", len(composed), len(decomposed))
print("equal ==:", composed == decomposed)

# NFC composes combining marks into single codepoints, so both spellings compare equal
nfc_a = unicodedata.normalize("NFC", composed)
nfc_b = unicodedata.normalize("NFC", decomposed)
print("nfc ==  :", nfc_a == nfc_b)
print("nfc len :", len(nfc_b))
print("pts     :", [hex(ord(c)) for c in decomposed])
print("nfc pts :", [hex(ord(c)) for c in nfc_b])

What the code does

Top-level bindings composed, decomposed, nfc_a, nfc_b hold the demo state — nothing sits inside a function scope.

Watch out for

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

Using it

The demo output is labeled (lengths :, equal ==:, nfc == :), so every printed line maps back to its originating operation.

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Yes: `unicodedata` must be present in the project or the import fails at load time.