views:

52

answers:

2

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'
>>>
A: 
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
Some people, when confronted with a problem, think“I know, I'll use regular expressions.” Now they have two problems.
Jon-Eric
+1  A: 

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
gnibbler
Hmm, the implicit assumption is that I want to preserve the case for the input string. Your solution will not preserve case.
Sridhar Ratnakumar
@Sridhar, I added a case insensitive version using regex. You should not be escaping `b` as you are not using it as a regex, just `a`
gnibbler
Marking this as the answer because it is simpler than my solution.
Sridhar Ratnakumar