Case-insensitive string equality

Chris Angelico rosuav at gmail.com
Thu Aug 31 09:30:21 EDT 2017


On Thu, Aug 31, 2017 at 10:49 PM, Steve D'Aprano
<steve+python at pearwood.info> wrote:
> On Thu, 31 Aug 2017 05:51 pm, Serhiy Storchaka wrote:
>
>> 31.08.17 10:10, Steven D'Aprano пише:
>>> (iii) Not every two line function needs to be in the standard library.
>>> Just add this to the top of every module:
>>>
>>> def equal(s, t):
>>>      return s.casefold() == t.casefold()
>>
>> This is my answer.
>>
>>> Unsolved problems:
>>>
>>> This proposal doesn't help with sets and dicts, list.index and the `in`
>>> operator either.
>>
>> This is the end of the discussion.
>
> Your answer of an equal() function doesn't help with sets and dicts either.
>
> So I guess we're stuck with no good standard answer:
>
> - the easy two-line function doesn't even come close to solving the problem
>   of case-insensitive string operations;
>
> - but we can't have case-insensitive string operations because too many
>   people say "just use this two-line function".

The method you proposed seems a little odd - it steps through the
strings character by character and casefolds them separately. How is
it superior to the two-line function? And it still doesn't solve any
of your other cases.

To make dicts/sets case insensitive, you really need something that
people have periodically asked for: a dict with a key function. It
would retain the actual key used, but for comparison purposes, would
use the modified version. Then you could use str.casefold as your key
function, and voila, you have a case insensitive dict.

I don't know if that would solve your other problems though.

ChrisA



More information about the Python-list mailing list