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?
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'
For the sport of it, without importing anything:
text = text.split(' ')
for i, s in enumerate(text): text[i] = 'August' if s.lower() == 'month' else text[i]
print((' ').join(text))
This will replace every occurence of s
by August
if s.lower()
equals month
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.