Case-insensitive string comparison

Alex Martelli aleax at aleax.it
Tue Apr 15 11:17:31 EDT 2003


Duncan Booth wrote:

> Alex Martelli <aleax at aleax.it> wrote in
> news:jJUma.23762$T34.707989 at news2.tin.it:
> 
>> import re
> listofnames = [re.escape(n) for n in listofnames]
>> namesre = re.compile('(%s)'%')|('.join(listofnames), re.I)
>> 
>> for m in namesre.finditer(astring):
>>     dosomething(astring, listofnames[m.lastindex-1])
>> 
>> 
> 
> I suggest adding the line above to avoid any nasty surprises (or use a
> different variable if you don't want to clobber listofnames).

If the "names" can include punctuation, that's definitely wise.  I
had taken "names" to be basically the same as "identifiers", but if
e.g. "c++" is a ``name'', then Duncan's precaution is warranted.


Alex





More information about the Python-list mailing list