Reputation: 110969
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()?
Upvotes: 4
Views: 2704
Reputation: 476
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 insensitive. Also note the r'...'
string literal for the regexp (which in this specific case is redundant but helps as soon as you use a regexp that has backslashes (\)
in them.
Upvotes: 6