How do I do a case-insensitive string comparison?

前端 未结 9 2388
无人及你
无人及你 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:37

    I saw this solution here using regex.

    import re
    if re.search('mandy', 'Mandy Pande', re.IGNORECASE):
    # is True
    

    It works well with accents

    In [42]: if re.search("ê","ê", re.IGNORECASE):
    ....:        print(1)
    ....:
    1
    

    However, it doesn't work with unicode characters case-insensitive. Thank you @Rhymoid for pointing out that as my understanding was that it needs the exact symbol, for the case to be true. The output is as follows:

    In [36]: "ß".lower()
    Out[36]: 'ß'
    In [37]: "ß".upper()
    Out[37]: 'SS'
    In [38]: "ß".upper().lower()
    Out[38]: 'ss'
    In [39]: if re.search("ß","ßß", re.IGNORECASE):
    ....:        print(1)
    ....:
    1
    In [40]: if re.search("SS","ßß", re.IGNORECASE):
    ....:        print(1)
    ....:
    In [41]: if re.search("ß","SS", re.IGNORECASE):
    ....:        print(1)
    ....:
    

提交回复
热议问题