How do I do a case-insensitive string comparison?

前端 未结 9 2193
无人及你
无人及你 2020-11-21 07:46

How can I do case insensitive string comparison in Python?

I would like to encapsulate comparison of a regular strings to a repository string using in a very simple

9条回答
  •  花落未央
    2020-11-21 08:21

    Section 3.13 of the Unicode standard defines algorithms for caseless matching.

    X.casefold() == Y.casefold() in Python 3 implements the "default caseless matching" (D144).

    Casefolding does not preserve the normalization of strings in all instances and therefore the normalization needs to be done ('å' vs. 'å'). D145 introduces "canonical caseless matching":

    import unicodedata
    
    def NFD(text):
        return unicodedata.normalize('NFD', text)
    
    def canonical_caseless(text):
        return NFD(NFD(text).casefold())
    

    NFD() is called twice for very infrequent edge cases involving U+0345 character.

    Example:

    >>> 'å'.casefold() == 'å'.casefold()
    False
    >>> canonical_caseless('å') == canonical_caseless('å')
    True
    

    There are also compatibility caseless matching (D146) for cases such as '㎒' (U+3392) and "identifier caseless matching" to simplify and optimize caseless matching of identifiers.

提交回复
热议问题