1

This question is similar to this except that the substring to be replaced is only known at the runtime.

I want to write the definition of ireplace, that behaves like this:

>>> ireplace(r'c:\Python26\lib\site.py', r'C:\python26', r'image\python26')
r'image\python26\lib\site.py'
>>>
Community
  • 1
  • 1
Sridhar Ratnakumar
  • 81,433
  • 63
  • 146
  • 187

2 Answers2

1

In this case, I think this is the simplest way

r'c:\Python26\lib\site.py'.lower().replace('python26', r'image\python26')

For case insensitive, regexp is the simplest way

>>> def ireplace(s, a, b):
...     return re.sub("(?i)"+re.escape(a),b,s)
...
>>> print ireplace(r'c:\Python26\lib\site.py', 'C:\python26', r'image\python26')
image\python26\lib\site.py
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0
def ireplace(s, a, b):
    """Replace `a` with `b` in s without caring about case"""
    re_a = re.compile(re.escape(a), re.IGNORECASE)
    return re_a.sub(lambda m: b, s)

Note: The lambda m: b hack is necessary, as re.escape(b) seems to mangle the string if it it has hyphens.

Sridhar Ratnakumar
  • 81,433
  • 63
  • 146
  • 187
  • Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems. – Jon-Eric Jul 30 '10 at 00:08