tags:

views:

320

answers:

3

I know that you can use the ctypes library to perform case insensitive comparisons on strings, however I would like to perform case insensitive replacement too. Currently the only way I know to do this is with Regex's and it seems a little poor to do so via that.

Is there a case insensitive version of replace()?

+1  A: 

The easiest way is to convert it all to lowercase then do the replace. But is obviously an issue if you want to retain the original case.

I would do a regex replace, you can instruct the Regex engine to ignore casing all together.

See this site for an example.

Skurmedel
+9  A: 

You can supply the flag re.IGNORECASE to functions in the re module as described in the docs.

matcher = re.compile(myExpression, re.IGNORECASE)
zdan
Surely re.sub would be better?
Teifion
You would use the object returned by compile as the pattern in re.sub.
zdan
Ahhh, and if I were using it a lot then it'd be faster. Thanks!
Teifion
+2  A: 

Using re is the best solution even if you think it's complicated.

To replace all occurrences of 'abc', 'ABC', 'Abc', etc., with 'Python', say:

re.sub(r'(?i)abc', 'Python', a)

Example session:

>>> a = 'abc  asd   Abc  asd  ABCDE    XXAbCXX'
>>> import re
>>> re.sub(r'(?i)abc', 'Python', a)
'Python  asd   Python  asd  PythonDE    XXPythonXX'
>>>

Note how embedding (?i) at the start of the regexp makes it case sensitive. Also note the r'...' string literal for the regexp (which in this specific case is redundant but helps as soon as your regexp has backslashes (\) in them.