Filip Eriksson Filip Eriksson - 4 months ago 11
Python Question

Python replace string (upper or lower case) with another string

I want to replace the word ?Month in a text with the word August.

text=text.replace('?Month','August')


The issue is that I don't want upper or lower case to matter in ?Month. Regardless if ?Month is upper or lower case (or a mixture) it shall be overwritten with August. See the examples below:

E.g: ?Month ->August
?month -> August
?MONTH -> August
?moNth -> August


How do I do that?

Answer

Use a regular expression (via the re module):

import re

text = re.sub(r'\?month', 'August', text, flags=re.IGNORECASE)

The re.IGNORECASE flag tells the regular expression engine to match text case-insensitively:

>>> import re
>>> text = 'Demo: ?Month ?month ?MONTH ?moNth'
>>> re.sub(r'\?month', 'August', text, flags=re.IGNORECASE)
'Demo: August August August August'
Comments