case insensitive comparison operator ?

Max M maxm at mxm.dk
Wed Aug 18 13:34:13 CEST 2004


Will McGugan wrote:

> What is the best way to do a simple case insensitive comparison in Python?
> 
> As far as I can tell, the only option is to do str1.lowercase() == 
> str2.lowercase() (or uppercase). But that strikes me as quite verbose 
> for such a common operation, and possibly inneficient since it would 
> create and destroy 2 tempory objects. Perhaps there should be a 
> dedicated function in the string object, or (+1) an operator?


How else could it be done?

You could wrap it in a function, and reuse the code if you want to. That 
way you can imagine that it never happens ;-)

def cic(x,y);
     "Case insensitive compare"
     return x.lower() == y.lower()

But you cannot really do it any more efficient.

Forget your worries. It's probably just a case of premature optimisation.

Naturally there are special cases where you must do it more efficiently. 
But they would probably need to be solved based on the specific problem.

regards Max M



More information about the Python-list mailing list