开发者

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:\py开发者_如何学JAVAthon26', r'image\python26')
r'image\python26\lib\site.py'
>>>


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜