目录

方法一 正则表达式

方法二 字符串直接操作


方法一 正则表达式

str.replace(old, new[, max])的替换是区分大小写的

不区分大小写替换需要正则表达式re.sub()带上re.IGNORECASE选项

>>> import re
>>> reg = re.compile(re.escape('hello'), re.IGNORECASE)
>>> reg.sub('My', 'Hello World, HELLO PYTHON')
'My World, My PYTHON'

方法二 字符串直接操作

def replace_case(old, new, text):
    index = text.lower().find(old.lower())
    if index == -1:
        return text
    return replace_case(old, new, text[:index] + new + text[index + len(old):])

dest="Hello World, HELLO PYTHON"
print(dest)
print(replace_case("hello", "My", dest))

输出:

Hello World, HELLO PYTHON
My World, My PYTHON