Algorithm Search⌘K

Algorithmcore

Unicode case folding

Also called caseless matching, full case folding.

Map each code point to its folding from CaseFolding.txt, so that strings that differ only in case become equal. Full folding can change the length: ß becomes ss.

Time
Θ(n) worst · best
Space
Θ(n) extra
Where
n = the length of the input in code points
Properties
deterministiconlineiterative

Unicode case folding maps a string to a form in which the differences of letter case are gone, so that two strings that differ only in case become equal. It replaces each code point by its mapping in the file CaseFolding.txt of the Unicode Character Database, and keeps code points that have no mapping. Full folding can make a string longer: U+00DF LATIN SMALL LETTER SHARP S (ß) becomes "ss". Simple folding keeps the length in code points. Folding is the base of caseless matching, and the canonical form of caseless matching also needs normalization before and after the folding.

In plain words

To compare words without caring about capital letters, people often turn both words into small letters first. For English this is enough. For other languages it is not. The German letter ß has no single capital form in common use, and its capital spelling is "SS", so "Straße" and "STRASSE" must become the same. Greek has two small forms of sigma, one used only at the end of a word, and both must become the same letter.

Unicode publishes one table that says, for each character, what it becomes in the case-free form. The method is to look up each character in the table and write down the result. A few results are two or three characters long. The table is fixed and the same for all languages, except an optional rule for the Turkish dotted and dotless i.

The problem

The input is a string XX of nn code points. The output is toCasefold(X)\mathrm{toCasefold}(X), defined by rule R4 of the core specification, section 3.13.3: "Map each character C in X to Case_Folding(C)." Here Case_Folding(C) is the mapping of C in CaseFolding.txt, or C itself if the file has no line for C.

Each line of CaseFolding.txt has the form code; status; mapping; # name. The status says which kind of folding uses the line:

  • C (common): a mapping to one code point, used by full and by simple folding.
  • F (full): a mapping to two or three code points, used by full folding.
  • S (simple): a mapping to one code point, used by simple folding where an F line exists for the same code point.
  • T (Turkic): a special mapping for U+0049 and U+0130, used only if the caller asks for it. It is not part of the default folding.

Full folding uses the lines with status C and F. Simple folding uses C and S. The default case folding of the standard is full folding without the T lines. Python's str.casefold computes it.

Two strings are a default caseless match (D144) if toCasefold(X)=toCasefold(Y)\mathrm{toCasefold}(X) = \mathrm{toCasefold}(Y). They are a canonical caseless match (D145) if

NFD(toCasefold(NFD(X)))=NFD(toCasefold(NFD(Y))).\mathrm{NFD}(\mathrm{toCasefold}(\mathrm{NFD}(X))) = \mathrm{NFD}(\mathrm{toCasefold}(\mathrm{NFD}(Y))).

D146 (compatibility caseless match) uses NFKD in the same way, and D147 (identifier caseless match) uses the derived mapping toNFKC_Casefold. Here NFD is the canonical decomposition of the normalization algorithm.

The algorithm

  1. TO-CASEFOLD(X, full, turkic)
  2. 1Y <- empty string
  3. 2for each code point c of X do
  4. 3if turkic and c has a line with status T then append its mapping to Y
  5. 4else if full and c has a line with status F then append its mapping to Y
  6. 5else if not full and c has a line with status S then append its mapping to Y
  7. 6else if c has a line with status C then append its mapping to Y
  8. 7else append c to Y
  9. 8return Y
  10. CANONICAL-CASELESS-MATCH(X, Y)
  11. 9return NFD(TO-CASEFOLD(NFD(X))) = NFD(TO-CASEFOLD(NFD(Y)))

The table is a hash table or a two-stage array keyed by code point. For each code point, CaseFolding.txt has at most one line of each status, and it never has both an F line and a C line for the same code point, so lines L3 to L7 pick exactly one result. The implementation copies the lines it uses verbatim from CaseFolding-16.0.0.txt, among them the C, F, S and T lines of ß, U+1E9E LATIN CAPITAL LETTER SHARP S (ẞ), U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE (İ), U+0049, U+03C2 GREEK SMALL LETTER FINAL SIGMA (ς), U+01C5 LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON (Dž) and U+0345 COMBINING GREEK YPOGEGRAMMENI.

Example

The values below come from the lines of CaseFolding-16.0.0.txt in the implementation, and str.casefold gives the same full foldings.

input code points full folding simple folding
Straße 0053 0074 0072 0061 00DF 0065 0073 0074 0072 0061 0073 0073 0065 (strasse) 0073 0074 0072 0061 00DF 0065 (straße)
STRASSE 0053 0054 0052 0041 0053 0053 0045 strasse strasse
ẞ 1E9E 0073 0073 00DF
ffi FB03 0066 0066 0069 FB03
İ 0130 0069 0307 0130
Dž 01C5 01C6 01C6
ς 03C2 03C3 03C3

"Straße" and "STRASSE" are a default caseless match under full folding, but not under simple folding. Folding is not lowercasing: U+00DF is already small and still changes, and U+0130 has no simple folding at all, so simple folding keeps it. With the Turkic option, U+0049 folds to U+0131 LATIN SMALL LETTER DOTLESS I and U+0130 folds to U+0069.

Why D145 normalizes first. Take XX = U+03B1 U+0345 U+0301 and YY = U+03B1 U+0301 U+0345. The marks U+0345 and U+0301 have the canonical combining classes 240 and 230, so NFD puts U+0301 first, and XX and YY are canonically equivalent. U+0345 folds to U+03B9 GREEK SMALL LETTER IOTA, which is a starter. Folding first gives U+03B1 U+03B9 U+0301 for XX and U+03B1 U+0301 U+03B9 for YY. NFD cannot move the acute accent across the starter U+03B9, so the two results stay different. With NFD first, both strings become U+03B1 U+0301 U+0345, and both fold to U+03B1 U+0301 U+03B9. The core specification gives this case as the reason: "Normalization is not required before case folding, except for the character U+0345".

Why D145 normalizes after. U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE folds to U+00E5, but U+0041 U+030A folds to U+0061 U+030A. The two folded strings are canonically equivalent but not equal, so only the final NFD makes them match. Also, U+0390 GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS is in NFC, but its full folding U+03B9 U+0308 U+0301 is not: folding does not keep a string normalized.

Correctness

TO-CASEFOLD computes R4 directly. The loop of lines L2 to L7 keeps the invariant that YY is the concatenation of Case_Folding(c) over the code points already read, where Case_Folding is taken with the statuses that the options select. The selection is well defined because the file has at most one line per code point and status, and never both C and F for one code point. At the end, Y=toCasefold(X)Y = \mathrm{toCasefold}(X). Simple folding keeps the length because every C and S mapping is one code point. The canonical caseless match of line L9 is an equivalence relation, because it compares the values of one function, and it contains canonical equivalence, because canonically equivalent strings have the same NFD. The full proof is in proofs/correctness.md.

Proof: TO-CASEFOLD computes toCasefold, and the canonical caseless match is an equivalence that contains canonical equivalencefull

Setup. Let TT be the set of lines of CaseFolding.txt. For a code point cc and a status ss in {C,F,S,T}\{C, F, S, T\}, write Ts(c)T_s(c) for the mapping of the line of cc with status ss, if there is one. The file has two properties that the proof uses. (P1) For each cc and ss there is at most one line. (P2) No code point has both a C line and an F line, and no code point has both a C line and an S line. (P2) is how the file is built: the header says that a C line is used by both kinds of folding, and F and S lines are given only where full and simple folding differ.

For the options full and turkic, define the folding of one code point:

  • f(c)=TT(c)f(c) = T_T(c) if turkic holds and TT(c)T_T(c) exists;
  • otherwise f(c)=TF(c)f(c) = T_F(c) if full holds and TF(c)T_F(c) exists;
  • otherwise f(c)=TS(c)f(c) = T_S(c) if full does not hold and TS(c)T_S(c) exists;
  • otherwise f(c)=TC(c)f(c) = T_C(c) if it exists;
  • otherwise f(c)=cf(c) = c.

By (P1), each case gives one string, so ff is a function. With full = true and turkic = false, f(c)f(c) is Case_Folding(c) of the default full folding (statuses C and F), and R4 defines toCasefold(X)=f(x0)f(x1)⋯f(xn−1)\mathrm{toCasefold}(X) = f(x_0) f(x_1) \cdots f(x_{n-1}) for X=x0⋯xn−1X = x_0 \cdots x_{n-1}. With full = false, ff is the simple folding (statuses C and S).

Claim 1. TO-CASEFOLD(X,full,turkic)(X, \mathrm{full}, \mathrm{turkic}) stops and returns f(x0)⋯f(xn−1)f(x_0) \cdots f(x_{n-1}).

Proof. The loop of line L2 runs once for each of the nn code points, and each iteration does a bounded number of steps, so the procedure stops. Invariant: before the iteration for xix_i, Y=f(x0)⋯f(xi−1)Y = f(x_0) \cdots f(x_{i-1}). It holds for i=0i = 0 by line L1. In the iteration for xix_i, lines L3 to L7 test the same conditions in the same order as the definition of ff and append the same string, so after it Y=f(x0)⋯f(xi)Y = f(x_0) \cdots f(x_i). For i=ni = n, line L8 returns f(x0)⋯f(xn−1)f(x_0) \cdots f(x_{n-1}). □\square

Claim 2. Simple folding keeps the length in code points.

Proof. With full = false and turkic = false, line L4 is never taken, so each code point appends TS(c)T_S(c), TC(c)T_C(c) or cc. Every S and C mapping in the file is one code point (the header defines both as mappings to single characters). So each iteration appends exactly one code point, and by Claim 1 the output has nn code points. □\square

Claim 3. Let K(X)=NFD(toCasefold(NFD(X)))K(X) = \mathrm{NFD}(\mathrm{toCasefold}(\mathrm{NFD}(X))). The relation "K(X)=K(Y)K(X) = K(Y)", which line L9 tests, is an equivalence relation. If XX and YY are canonically equivalent, then K(X)=K(Y)K(X) = K(Y).

Proof. The relation compares the values of one function KK, so it is reflexive, symmetric and transitive. If XX and YY are canonically equivalent, then NFD(X)=NFD(Y)\mathrm{NFD}(X) = \mathrm{NFD}(Y), because NFD is a normal form for canonical equivalence (the uniqueness of the normalization forms, core spec section 3.11). Then the two values of KK are computed from the same string and are equal. □\square

Claim 4. The default caseless match D144 does not contain canonical equivalence, so the NFD steps of D145 are needed.

Proof. A counterexample is enough. XX = U+00C5 and YY = U+0041 U+030A are canonically equivalent. By the C lines 00C5; C; 00E5; and 0041; C; 0061;, and since U+030A has no line, toCasefold(X)\mathrm{toCasefold}(X) = U+00E5 and toCasefold(Y)\mathrm{toCasefold}(Y) = U+0061 U+030A, which differ. The final NFD maps both to U+0061 U+030A. The first NFD is needed too: XX = U+03B1 U+0345 U+0301 and YY = U+03B1 U+0301 U+0345 are canonically equivalent (ccc\mathrm{ccc} 240 and 230), and NFD(toCasefold(X))\mathrm{NFD}(\mathrm{toCasefold}(X)) = U+03B1 U+03B9 U+0301 differs from NFD(toCasefold(Y))\mathrm{NFD}(\mathrm{toCasefold}(Y)) = U+03B1 U+0301 U+03B9, because U+03B9 has ccc=0\mathrm{ccc} = 0 and canonical ordering never moves a mark across a starter. □\square

Termination of line L9. NFD and TO-CASEFOLD stop on every finite input, and line L9 calls each a fixed number of times.

Complexity

In the word-RAM model, one lookup in a table indexed by code point costs O(1)O(1). The constant is large in practice: real tables use two or three levels of arrays to cover the 1,114,112 code points of the codespace.

  • Folding. Each code point costs one lookup and appends at most 3 code points, because no F mapping in CaseFolding.txt is longer than 3 code points. So TO-CASEFOLD takes Θ(n)\Theta(n) time, and the output has at most 3n3n code points.
  • Space. The output takes O(n)O(n) space. A comparison that folds both strings lazily, one code point at a time, needs only O(1)O(1) extra space.
  • Canonical caseless match. NFD costs O(n)O(n) lookups, plus the canonical ordering of each run of combining marks, which costs O(klog⁡k)O(k \log k) for a run of kk marks. Line L9 runs NFD twice and the folding once on each string.
claim value
time of TO-CASEFOLD Θ(n)\Theta(n) lookups
output length, full folding at most 3n3n code points
output length, simple folding exactly nn code points

Properties

  • Context-free. Each code point folds alone. There is no rule for the end of a word, unlike the lowercase mapping of U+03A3 GREEK CAPITAL LETTER SIGMA, which depends on the context.
  • Concatenation. toCasefold(XY)=toCasefold(X) toCasefold(Y)\mathrm{toCasefold}(XY) = \mathrm{toCasefold}(X)\,\mathrm{toCasefold}(Y). This makes the folding online and lets a program fold a stream in pieces.
  • Idempotent on the data. Folding a folded string changes nothing. The tests check this on every line of the table.
  • Not normalization-preserving. A string in NFC can fold to a string that is not in NFC, as U+0390 above.
  • Language-independent. The default folding is the same for all languages. Only the T lines depend on the language.

Variants and improvements

  • Simple folding. Statuses C and S. It keeps the length in code points and suits fixed-size buffers and regular expression engines that compare one code point with one code point.
  • Turkic folding. Put the T lines before the others, for Turkish and Azerbaijani.
  • Compatibility caseless match (D146). NFKD(toCasefold(NFKD(toCasefold(NFD(X)))))\mathrm{NFKD}(\mathrm{toCasefold}(\mathrm{NFKD}(\mathrm{toCasefold}(\mathrm{NFD}(X))))). It also matches compatibility variants, for example U+FB03 and "ffi", and the full-width letters.
  • Identifier caseless match (D147). It uses toNFKC_Casefold, a derived property of the Unicode Character Database that combines NFKC, folding and the removal of default ignorable code points in one mapping.
  • Lazy comparison. Compare two strings by folding each one code point at a time and comparing the outputs as streams. This needs no allocation.

When to use it

Use full default folding with the canonical match D145 when you compare user text without regard to case: search, deduplication of names, keys of a hash table that must ignore case. Use simple folding when the length must not change. Use the Turkic option only when you know the language of the text. Do not use folding to produce text for display: the folded string is a comparison key, not a lowercase version of the text. For sorting, use the collation algorithm, which treats case as a level 3 difference. For security checks of look-alike strings, use confusable detection, which goes further than case.

Pitfalls

  • Lowercasing instead of folding. A lowercase mapping keeps ß and maps ẞ to ß, so "STRASSE" and "Straße" do not match. The test test_check_values checks the full foldings of ß and ẞ.
  • Folding without normalization. U+00C5 and U+0041 U+030A do not match by D144. Use D145. The test test_default_match_misses_decomposed_forms shows this case.
  • Normalizing only after folding. The U+0345 example above fails. The test test_ypogegrammeni_needs_nfd_first checks it.
  • Turkic lines by default. Taking the T lines for all text makes "I" fold to dotless ı and breaks English. The test test_turkic_option checks both settings.
  • Fixed-size output buffers. Full folding can triple the length in code points, and more in bytes.
  • Characters that look cased but fold elsewhere. U+212A KELVIN SIGN folds to "k" and U+2126 OHM SIGN folds to U+03C9. A table built only from the letters A to Z misses them.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

unicode_case_folding.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unicode-case-folding/. The authors are listed in prov/GS7516.jsonl.

"""Unicode default case folding (core spec 16.0.0, section 3.13, R4) and caseless matching (D144, D145).

The table is a small part of CaseFolding-16.0.0.txt. The code does not call str.casefold,
str.lower or str.upper. It calls unicodedata.normalize only for NFD in D145.
"""

import unicodedata

# Lines copied verbatim from CaseFolding-16.0.0.txt (Date: 2024-04-30, 21:48:11 GMT),
# https://www.unicode.org/Public/16.0.0/ucd/CaseFolding.txt. Only the lines that the page
# and the tests use are here. The file is sorted by code point, and so is this list.
CASE_FOLDING_LINES = """\
0041; C; 0061; # LATIN CAPITAL LETTER A
0042; C; 0062; # LATIN CAPITAL LETTER B
0043; C; 0063; # LATIN CAPITAL LETTER C
0044; C; 0064; # LATIN CAPITAL LETTER D
0045; C; 0065; # LATIN CAPITAL LETTER E
0046; C; 0066; # LATIN CAPITAL LETTER F
0047; C; 0067; # LATIN CAPITAL LETTER G
0048; C; 0068; # LATIN CAPITAL LETTER H
0049; C; 0069; # LATIN CAPITAL LETTER I
0049; T; 0131; # LATIN CAPITAL LETTER I
004A; C; 006A; # LATIN CAPITAL LETTER J
004B; C; 006B; # LATIN CAPITAL LETTER K
004C; C; 006C; # LATIN CAPITAL LETTER L
004D; C; 006D; # LATIN CAPITAL LETTER M
004E; C; 006E; # LATIN CAPITAL LETTER N
004F; C; 006F; # LATIN CAPITAL LETTER O
0050; C; 0070; # LATIN CAPITAL LETTER P
0051; C; 0071; # LATIN CAPITAL LETTER Q
0052; C; 0072; # LATIN CAPITAL LETTER R
0053; C; 0073; # LATIN CAPITAL LETTER S
0054; C; 0074; # LATIN CAPITAL LETTER T
0055; C; 0075; # LATIN CAPITAL LETTER U
0056; C; 0076; # LATIN CAPITAL LETTER V
0057; C; 0077; # LATIN CAPITAL LETTER W
0058; C; 0078; # LATIN CAPITAL LETTER X
0059; C; 0079; # LATIN CAPITAL LETTER Y
005A; C; 007A; # LATIN CAPITAL LETTER Z
00B5; C; 03BC; # MICRO SIGN
00C5; C; 00E5; # LATIN CAPITAL LETTER A WITH RING ABOVE
00C9; C; 00E9; # LATIN CAPITAL LETTER E WITH ACUTE
00DF; F; 0073 0073; # LATIN SMALL LETTER SHARP S
0130; F; 0069 0307; # LATIN CAPITAL LETTER I WITH DOT ABOVE
0130; T; 0069; # LATIN CAPITAL LETTER I WITH DOT ABOVE
0149; F; 02BC 006E; # LATIN SMALL LETTER N PRECEDED BY APOSTROPHE
017F; C; 0073; # LATIN SMALL LETTER LONG S
01C4; C; 01C6; # LATIN CAPITAL LETTER DZ WITH CARON
01C5; C; 01C6; # LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON
01C7; C; 01C9; # LATIN CAPITAL LETTER LJ
01C8; C; 01C9; # LATIN CAPITAL LETTER L WITH SMALL LETTER J
0345; C; 03B9; # COMBINING GREEK YPOGEGRAMMENI
0390; F; 03B9 0308 0301; # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
03A3; C; 03C3; # GREEK CAPITAL LETTER SIGMA
03C2; C; 03C3; # GREEK SMALL LETTER FINAL SIGMA
03F4; C; 03B8; # GREEK CAPITAL THETA SYMBOL
0587; F; 0565 0582; # ARMENIAN SMALL LIGATURE ECH YIWN
1E9B; C; 1E61; # LATIN SMALL LETTER LONG S WITH DOT ABOVE
1E9E; F; 0073 0073; # LATIN CAPITAL LETTER SHARP S
1E9E; S; 00DF; # LATIN CAPITAL LETTER SHARP S
1F80; F; 1F00 03B9; # GREEK SMALL LETTER ALPHA WITH PSILI AND YPOGEGRAMMENI
1F88; F; 1F00 03B9; # GREEK CAPITAL LETTER ALPHA WITH PSILI AND PROSGEGRAMMENI
1F88; S; 1F80; # GREEK CAPITAL LETTER ALPHA WITH PSILI AND PROSGEGRAMMENI
1FB3; F; 03B1 03B9; # GREEK SMALL LETTER ALPHA WITH YPOGEGRAMMENI
1FBC; F; 03B1 03B9; # GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI
1FBC; S; 1FB3; # GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI
2126; C; 03C9; # OHM SIGN
212A; C; 006B; # KELVIN SIGN
212B; C; 00E5; # ANGSTROM SIGN
FB03; F; 0066 0066 0069; # LATIN SMALL LIGATURE FFI
FB05; F; 0073 0074; # LATIN SMALL LIGATURE LONG S T
FB05; S; FB06; # LATIN SMALL LIGATURE LONG S T
FB06; F; 0073 0074; # LATIN SMALL LIGATURE ST
"""


def parse_case_folding(text: str) -> dict[str, dict[str, str]]:
    """Parse lines in the CaseFolding.txt format: code; status; mapping; # name.

    Return a dict from a one-code-point string to a dict from status (C, F, S or T)
    to the mapped string.
    """
    table: dict[str, dict[str, str]] = {}
    for raw in text.splitlines():
        line = raw.split("#", 1)[0].strip()
        if not line:
            continue
        fields = [f.strip() for f in line.split(";")]
        code, status, mapping = fields[0], fields[1], fields[2]
        if status not in ("C", "F", "S", "T"):
            raise ValueError(f"unknown status {status!r} in {raw!r}")
        src = chr(int(code, 16))
        dst = "".join(chr(int(h, 16)) for h in mapping.split())
        table.setdefault(src, {})[status] = dst
    return table


CASE_FOLDING = parse_case_folding(CASE_FOLDING_LINES)


def to_casefold(x: str, full: bool = True, turkic: bool = False,
                table: dict[str, dict[str, str]] = CASE_FOLDING) -> str:
    """Return toCasefold(x): each code point is replaced by its case folding.

    full=True uses the statuses C and F (full folding, as str.casefold);
    full=False uses C and S (simple folding, which keeps the length in code points).
    turkic=True puts the T lines first (the dotted and dotless I of Turkish and Azerbaijani).
    A code point with no line maps to itself.
    """
    out: list[str] = []  # @line L1
    for c in x:  # @line L2
        entry = table.get(c)
        if entry is None:
            out.append(c)
            continue
        if turkic and "T" in entry:  # @line L3
            out.append(entry["T"])
        elif full and "F" in entry:  # @line L4
            out.append(entry["F"])
        elif not full and "S" in entry:  # @line L5
            out.append(entry["S"])
        elif "C" in entry:  # @line L6
            out.append(entry["C"])
        else:  # @line L7
            out.append(c)
    return "".join(out)  # @line L8


def default_caseless_match(x: str, y: str, turkic: bool = False) -> bool:
    """D144: toCasefold(x) = toCasefold(y), with full folding."""
    return to_casefold(x, turkic=turkic) == to_casefold(y, turkic=turkic)


def canonical_caseless_key(x: str, turkic: bool = False) -> str:
    """Return NFD(toCasefold(NFD(x))), the key of D145."""
    nfd = unicodedata.normalize("NFD", x)
    return unicodedata.normalize("NFD", to_casefold(nfd, turkic=turkic))


def canonical_caseless_match(x: str, y: str, turkic: bool = False) -> bool:
    """D145: NFD(toCasefold(NFD(x))) = NFD(toCasefold(NFD(y)))."""
    return canonical_caseless_key(x, turkic) == canonical_caseless_key(y, turkic)  # @line L9
test_unicode_case_folding.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unicode-case-folding/. The authors are listed in prov/GS7516.jsonl.

# The oracle is str.casefold, which is full case folding on the Unicode version of
# unicodedata.unidata_version (16.0.0 when these tests were written). The oracle tests use
# only characters assigned in Unicode 3.2, so a newer Python cannot change the result.

import random
import unicodedata

from unicode_case_folding import (
    CASE_FOLDING,
    canonical_caseless_key,
    canonical_caseless_match,
    default_caseless_match,
    to_casefold,
)


def in_3_2(c: str) -> bool:
    return unicodedata.ucd_3_2_0.category(c) != "Cn"


def test_check_values():
    assert to_casefold("ß") == "ss"
    assert to_casefold("ẞ") == "ss"
    assert to_casefold("ffi") == "ffi"
    assert to_casefold("İ") == "i̇"
    assert to_casefold("ς") == "σ"
    assert to_casefold("DŽ") == "dž"
    assert to_casefold("Dž") == "dž"


def test_against_str_casefold_on_table():
    checked = 0
    for c in CASE_FOLDING:
        if in_3_2(c):
            assert to_casefold(c) == c.casefold(), hex(ord(c))
            checked += 1
    assert checked >= 50


def test_random_strings_against_str_casefold():
    rng = random.Random(20240910)
    pool = [c for c in CASE_FOLDING if in_3_2(c)] + list("abcxyz éά")
    for _ in range(500):
        s = "".join(rng.choice(pool) for _ in range(rng.randint(0, 12)))
        assert to_casefold(s) == s.casefold()


def test_simple_folding_keeps_length():
    assert to_casefold("ẞ", full=False) == "ß"
    assert to_casefold("ß", full=False) == "ß"
    assert to_casefold("ᾼ", full=False) == "ᾳ"
    assert to_casefold("ſt", full=False) == "st"
    rng = random.Random(7)
    pool = list(CASE_FOLDING) + list("abc")
    for _ in range(300):
        s = "".join(rng.choice(pool) for _ in range(rng.randint(0, 10)))
        assert len(to_casefold(s, full=False)) == len(s)


def test_full_folding_changes_length():
    assert len("ΐ") == 1 and len(to_casefold("ΐ")) == 3
    assert to_casefold("Straße") == "strasse"


def test_turkic_option():
    assert to_casefold("I") == "i"
    assert to_casefold("I", turkic=True) == "ı"
    assert to_casefold("İ", turkic=True) == "i"
    assert not default_caseless_match("I", "ı")
    assert default_caseless_match("I", "ı", turkic=True)


def test_idempotent():
    for c in CASE_FOLDING:
        for full in (True, False):
            f = to_casefold(c, full=full)
            assert to_casefold(f, full=full) == f


def test_sign_characters():
    assert to_casefold("K") == "k"
    assert to_casefold("Ω") == "ω"
    assert to_casefold("Å") == "å"
    assert to_casefold("µ") == "μ"


def test_default_match_misses_decomposed_forms():
    assert not default_caseless_match("Å", "Å")
    assert canonical_caseless_match("Å", "Å")
    assert canonical_caseless_match("Å", "å")


def test_ypogegrammeni_needs_nfd_first():
    x = "ᾴ"
    y = "ᾴ"
    assert unicodedata.normalize("NFD", x) == unicodedata.normalize("NFD", y)
    folded_then_nfd_x = unicodedata.normalize("NFD", to_casefold(x))
    folded_then_nfd_y = unicodedata.normalize("NFD", to_casefold(y))
    assert folded_then_nfd_x != folded_then_nfd_y
    assert canonical_caseless_key(x) == "άι"
    assert canonical_caseless_match(x, y)


def test_folding_does_not_preserve_nfc():
    s = "ΐ"
    assert unicodedata.normalize("NFC", s) == s
    f = to_casefold(s)
    assert f == "ΐ"
    assert unicodedata.normalize("NFC", f) != f

History

In ASCII, case-insensitive comparison only maps A to Z onto a to z. Unicode added the file CaseFolding.txt to its Character Database so that all programs fold the same characters in the same way, with the full mappings for ß, the ligatures and the Greek letters with iota subscript. U+1E9E LATIN CAPITAL LETTER SHARP S came in Unicode 5.1 (2008). It folds to "ss" like ß, so the folding of German text did not change. Python added str.casefold in version 3.3.

References

  1. The Unicode Consortium, The Unicode Standard, Version 16.0.0, 2024, Chapter 3, Section 3.13 Default Case Algorithms: 3.13.3 Default Case Folding (R4, toCasefold) and 3.13.5 Default Caseless Matching (D144 to D147)
  2. The Unicode Standard, Version 16.0.0, core specification (online), Chapter 3, Section 3.13
  3. CaseFolding-16.0.0.txt, Unicode Character Database, the header (the status values C, F, S and T) and the data lines
  4. Python documentation, Built-in Types, str.casefold

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example