Case-Sensitive Sarch and replace

Richie Hindle richie at
Fri Jun 4 16:37:26 CEST 2004

> For example, if fn="AlphaMin.txt", searchstring="min" and
> replacestring= "Max", I want the file to be renamed "AlphaMax.txt" and
> not "alphaMax.txt" or "alphamax.txt"

Use case-insensitive regular expression replacement:

>>> import re
>>> def replace(filename, search, replace):
...     regex = '(?i)' + re.escape(search)
...     return re.sub(regex, replace, filename)
>>> replace("AlphaMin.txt", "min", "Max")

Richie Hindle
richie at

More information about the Python-list mailing list