PREP WITH PROOF
Menu
PYTHON & DATA ENGINEERING / PRACTICAL GUIDE

Python Unicode Matching: NFC, NFKC and Casefold Explained

Choose Unicode matching rules with NFC, NFKC and casefold. Inspect code points, detect collisions, preserve original text and avoid unsafe normalization assumptions.

THE QUICK ANSWER

Two strings can look identical and compare unequal, while two visibly different strings can become equal after normalization or case folding. The right fix is a documented matching policy, not an unconditional cleanup function. This guide separates canonical normalization, compatibility normalization, and caseless matching, then uses a complete Python lab to expose the collisions each policy creates without overwriting the original records.

Inspect the representation before changing it

Imagine importing two customer labels: one contains a precomposed accented letter and the other contains a base letter followed by a combining accent. A font may render them alike, but Python strings contain different sequences of code points. A direct equality test can therefore disagree with what a person sees. Start by inspecting escaped text and code points, not by replacing characters until the test passes.

Use ascii(text) to make many non-ASCII and invisible characters visible in diagnostic output, and unicodedata.name to label code points. Preserve a record identifier beside every observation. If a field contains personal information, keep such diagnostics in an appropriately restricted environment rather than copying entire production records into logs.

Decoding and normalization are separate operations. First decode incoming bytes using the declared encoding and an explicit error policy. A valid Unicode string can still need a matching policy; normalization cannot recover the intended text after an incorrect decoding step. Conversely, silently dropping undecodable bytes can create collisions before normalization even begins.

Source: Python 3.12: Unicode HOWTO and text representation ↗

Choose canonical or compatibility equivalence deliberately

NFC and NFD address canonical equivalence. For example, the precomposed é and e followed by COMBINING ACUTE ACCENT can be put into the same canonical representation. NFC composes where possible after canonical processing; NFD decomposes. Neither is a universal rule for deciding whether two business records represent the same entity.

NFKC and NFKD additionally apply compatibility mappings. Fullwidth Latin letters can become ordinary Latin letters, and a circled digit can become a plain digit. That may be helpful for a restricted search field. It may also erase a distinction that matters in a product code, mathematical label, or faithfully reproduced document. Keep the original text whenever that distinction may be needed later.

The table shows normalization alone, before any case folding. The distinction matters because a later transformation can introduce its own merges. Do not assume that selecting NFC means every other stage in your pipeline preserves compatibility distinctions.

InputNFC resultNFKC result
Café / Cafe + combining acuteSame composed CaféSame composed Café
Fullwidth ABCFullwidth ABCABC
Circled digit ①①1
Nonbreaking space U+00A0U+00A0Ordinary space U+0020

Source: Unicode UAX #15: normalization forms and boundaries ↗

Casefold is a matching transformation, not just lowercase

Python’s casefold method is designed for caseless matching. It is more aggressive than lower: Straße and STRASSE can share the key strasse, even though lower alone leaves the sharp s in the first value. This is a useful comparison rule only if your application intends those values to match.

Default case folding is not locale-specific collation. For example, the capital dotted İ folds to i followed by a combining dot, which remains distinct from plain i in the example policies. Do not label a default casefold key as a complete Turkish-language search implementation. Likewise, matching keys do not provide a language-aware sort order.

Apply transformations in a specified order and normalize the result again where your policy requires it. The lab defines one key using canonical decomposition, default case folding, and NFC output. Its second key uses NFKC, default case folding, and NFKC output. These are explicit application pipelines, so a future maintainer can reproduce exactly what a stored key means.

Source: Python: str.casefold semantics ↗

Run a collision audit before making keys unique

Save this as unicode_lab.py and run python unicode_lab.py. It uses only the standard library. The first output line identifies the Python and Unicode database versions. Each synthetic input is printed in escaped form with code-point names. The final sections report groups where different originals map to the same key.

The records intentionally include accents, sharp s, fullwidth letters, a circled digit, dotted I, a Cyrillic letter, and a zero-width space. Numeric record IDs let you follow each input through a collision. The buckets preserve every original instead of assigning one value per key and silently keeping only the last record.

The compatibility function is not an implementation of Unicode NFKC_Casefold. In particular, this simple pipeline retains some default-ignorable characters, including the zero-width space in this fixture. If a protocol requires the standardized operation or an identifier profile, implement that exact specification with a suitable conformant library rather than renaming this helper.

import sys
import unicodedata as ud

def nfc_fold(text):
    # A defined caseless key with canonical normalization.
    return ud.normalize("NFC", ud.normalize("NFD", text).casefold())

def compatibility_fold(text):
    # Application policy, NOT the Unicode NFKC_Casefold operation.
    return ud.normalize("NFKC", ud.normalize("NFKC", text).casefold())

def group_records(records, key_function):
    buckets = {}
    for record_id, original in records:
        key = key_function(original)
        buckets.setdefault(key, []).append((record_id, original))
    return buckets

def describe(text):
    return [f"U+{ord(ch):04X} {ud.name(ch, '<unnamed>')}" for ch in text]

if __name__ == "__main__":
    records = [
        (1, "Caf\u00e9"), (2, "Cafe\u0301"),
        (3, "Stra\u00dfe"), (4, "STRASSE"),
        (5, "\uff21\uff22\uff23"), (6, "ABC"),
        (7, "\u2460"), (8, "1"),
        (9, "A"), (10, "\u0410"),
        (11, "\u0130"), (12, "i"), (13, "i\u0307"),
        (14, "ab\u200b"), (15, "ab"),
    ]
    print("Python", sys.version.split()[0], "UCD", ud.unidata_version)
    for record_id, original in records:
        print(record_id, ascii(original), describe(original))
    for label, function in (("nfc-fold-v1", nfc_fold),
                            ("compat-fold-v1", compatibility_fold)):
        print(label)
        for key, members in group_records(records, function).items():
            if len({original for _, original in members}) > 1:
                print("collision", ascii(key), [record_id for record_id, _ in members])

Read a collision as evidence for review

Under the canonical caseless policy, the two Café records share a key, as do Straße and STRASSE. Under the compatibility policy, fullwidth ABC and ASCII ABC also share a key, and the circled digit joins the plain digit. These results tell you what the policy discards. They do not prove that the corresponding records should be merged.

Before adding a unique database constraint, compute candidate keys for existing rows and produce a collision report with stable IDs. Resolve those groups through the appropriate business process. If two accounts collapse to one proposed key, automatically choosing the older row or the most recently imported row can assign data to the wrong person.

Keep display text separate from matching keys. A search result can present the user’s original label while using a derived key for retrieval. Version the key policy, and decide what to do when multiple records match. If ambiguity is expected, return candidates rather than pretending a normalization pipeline creates an authoritative identity system.

Apply the same versioned policy to both incoming queries and indexed values. Normalizing only at ingestion or only at lookup creates inconsistent behavior. Database collation, application matching, and any external search engine must be tested together; a Python equality result does not establish how a database unique index will compare strings.

Know what these transformations leave unresolved

Latin A and Cyrillic А remain different under both lab policies. They are separate characters despite their similar appearance in many fonts. Normalization is not a general confusable-character detector. For security-sensitive identifiers, review an appropriate identifier and script policy rather than deleting every non-ASCII character or assuming NFKC prevents impersonation.

Neither pipeline removes accents generally, transliterates languages, collapses arbitrary whitespace, or strips all format characters. Those would be additional decisions with additional collisions. A zero-width character left in a key can explain a failed match; removing it everywhere can also break legitimate text. Inspect the field’s contract before adding another cleanup step.

Do not retroactively apply a new normalization rule to passwords, signed payloads, cryptographic hashes, or externally defined identifiers. Follow the exact contract for that system. Changing text before signature verification, for example, changes the bytes being verified. A helpful search-key transformation is not automatically appropriate for authentication or protocol processing.

Source: Unicode UTS #39: identifier security and confusables ↗

Normalize the complete field after assembling it

Normalizing two fragments separately does not guarantee that their concatenation is normalized. A fragment ending in e and another beginning with a combining acute accent can each be NFC on its own, while their concatenation still needs composition. This matters when a pipeline joins fields, appends suffixes, or processes streamed text in arbitrary chunks.

The short check below illustrates the boundary. For ordinary-sized application fields, assemble the intended complete value and apply the chosen normalization policy at that boundary. A streaming implementation needs a deliberate normalization boundary strategy; blindly normalizing each incoming byte chunk also risks splitting an encoded character before decoding.

Validate length and storage limits against the actual representations your system uses. Case folding can expand a character into multiple code points, and UTF-8 bytes are not the same measure as Python string length. A database column sized for raw input may need a different limit for its derived key. Test the final key rather than estimating from the display string.

import unicodedata as ud

left = ud.normalize("NFC", "e")
right = ud.normalize("NFC", "\u0301")
joined = left + right
assert joined != ud.normalize("NFC", joined)
assert ud.normalize("NFC", joined) == "\u00e9"
assert len("ß".casefold()) == 2
print(ascii(joined), ascii(ud.normalize("NFC", joined)))

Source: Unicode UAX #15: normalization forms and boundaries ↗

Make the matching policy an observable contract

The local checks for this guide used Python 3.12.14 with Unicode database 15.0.0. They verified fixed expected outputs, canonical-equivalent spellings, preserved collision members, and examples that must remain distinct. The published lab and concatenation snippet were executed. This is not a full Unicode conformance test or an audit of a database collation or authentication system.

Record unicodedata.unidata_version along with a persistent key-policy version. When upgrading the runtime or changing the pipeline, compare old and new keys on a representative corpus before rebuilding indexes. Keep a migration report, a collision-resolution decision, and a rollback path. Retaining originals makes it possible to recompute keys instead of trying to reverse a lossy transformation.

A useful acceptance set contains pairs that should match, pairs that must not match, empty and whitespace-containing inputs, combining marks at join boundaries, and compatibility characters that matter to your domain. Run the same set through ingestion, indexing, queries, and export. The result should explain why a match happened and retain enough evidence to correct the policy when it was wrong.

Inspect normalization in your browser

Use the free Unicode normalization inspector linked below to compare NFC, NFD, NFKC and NFKD with the original text preserved. It shows escaped values, code-point positions, UTF-16 units and UTF-8 byte counts. It performs normalization only; the Python casefold pipelines in this guide are separate matching policies.

KEEP THESE THREE THINGS

Your next steps

  1. Separate decoding, normalization, case folding and business identity decisions.
  2. NFKC can erase meaningful distinctions; preserve originals and audit collisions.
  3. A custom matching key is not a complete identifier-security or locale-collation solution.

Sources & official resources

Linked resources checked on 2026-10-28. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →