Sridhar Ratnakumar
Sridhar Ratnakumar

Reputation: 85352

How to replace a non-static substring case-insensitively

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'
>>>

Upvotes: 1

Views: 215

Answers (2)

John La Rooy
John La Rooy

Reputation: 304147

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

Upvotes: 1

Sridhar Ratnakumar
Sridhar Ratnakumar

Reputation: 85352

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.

Upvotes: 0

Related Questions