Case-Sensitive Sarch and replace

Richie Hindle richie at entrian.com
Fri Jun 4 10:37:26 EDT 2004


[Thomas]
> 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")
'AlphaMax.txt'

-- 
Richie Hindle
richie at entrian.com





More information about the Python-list mailing list