Case-insensitive string equality

Rhodri James rhodri at kynesim.co.uk
Thu Aug 31 06:15:16 EDT 2017


On 31/08/17 08:10, Steven D'Aprano wrote:
> So I'd like to propose some additions to 3.7 or 3.8. If the feedback here
> is positive, I'll take it to Python-Ideas for the negative feedback :-)
> 
> 
> (1) Add a new string method, which performs a case-insensitive equality
> test. Here is a potential implementation, written in pure Python:
> 
> 
> def equal(self, other):
>      if self is other:
>          return True
>      if not isinstance(other, str):
>          raise TypeError
>      if len(self) != len(other):
>          return False
>      casefold = str.casefold
>      for a, b in zip(self, other):
>          if casefold(a) != casefold(b):
>              return False
>      return True

I'd quibble about the name and the implementation (length is not 
preserved under casefolding), but I'd go for this.  The number of times 
I've written something like this in different languages...

> Alternatively: how about a === triple-equals operator to do the same
> thing?

Much less keen on new syntax, especially when other languages use it for 
other purposes.

> (2) Add keyword-only arguments to str.find and str.index:
> 
>      casefold=False
> 
>      which does nothing if false (the default), and switches to a case-
>      insensitive search if true.

There's an implementation argument to be had about whether separate 
casefolded methods would be better, but yes.

> Unsolved problems:
> 
> This proposal doesn't help with sets and dicts, list.index and the `in`
> operator either.

The only way I can think of to get much traction with this is to have a 
separate case-insensitive string class.  That feels a bit heavyweight, 
though.

-- 
Rhodri James *-* Kynesim Ltd



More information about the Python-list mailing list