Teifion
Teifion

Reputation: 110969

Case insensitivity in Python strings

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

Answers (3)

user95975
user95975

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

zdan
zdan

Reputation: 29450

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

matcher = re.compile(myExpression, re.IGNORECASE)

Upvotes: 10

Skurmedel
Skurmedel

Reputation: 22149

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.

Upvotes: 1

Related Questions