在Python中做不区分大小写的字符串替换最简单的方法是什么?


当前回答

继续bFloch的回答,这个函数将以不区分大小写的方式改变旧与新,而不是一个。

def ireplace(old, new, text):
    idx = 0
    while idx < len(text):
        index_l = text.lower().find(old.lower(), idx)
        if index_l == -1:
            return text
        text = text[:index_l] + new + text[index_l + len(old):]
        idx = index_l + len(new) 
    return text

其他回答

i='I want a hIPpo for my birthday'
key='hippo'
swp='giraffe'

o=(i.lower().split(key))
c=0
p=0
for w in o:
    o[c]=i[p:p+len(w)]
    p=p+len(key+w)
    c+=1
print(swp.join(o))

字符串类型不支持这一点。你可能最好使用正则表达式子方法和re.IGNORECASE选项。

>>> import re
>>> insensitive_hippo = re.compile(re.escape('hippo'), re.IGNORECASE)
>>> insensitive_hippo.sub('giraffe', 'I want a hIPpo for my birthday')
'I want a giraffe for my birthday'

这个函数同时使用str.replace()和re.findall()函数。 它将以不区分大小写的方式将字符串中出现的pattern替换为repl。

def replace_all(pattern, repl, string) -> str:
   occurences = re.findall(pattern, string, re.IGNORECASE)
   for occurence in occurences:
       string = string.replace(occurence, repl)
       return string

我有\t被转换为转义序列(向下滚动一点),所以我注意到re.sub将反切转义字符转换为转义序列。

为了防止这种情况的发生,我写了以下内容:

替换不区分大小写。

import re
    def ireplace(findtxt, replacetxt, data):
        return replacetxt.join(  re.compile(findtxt, flags=re.I).split(data)  )

同样,如果你想用转义字符替换它,就像这里的其他答案一样,将特殊含义的bashslash字符转换为转义序列,只需解码你的find and或replace字符串。在Python 3中,可能必须执行类似.decode("unicode_escape") # python3这样的操作

findtxt = findtxt.decode('string_escape') # python2
replacetxt = replacetxt.decode('string_escape') # python2
data = ireplace(findtxt, replacetxt, data)

在Python 2.7.8中测试

继续bFloch的回答,这个函数将以不区分大小写的方式改变旧与新,而不是一个。

def ireplace(old, new, text):
    idx = 0
    while idx < len(text):
        index_l = text.lower().find(old.lower(), idx)
        if index_l == -1:
            return text
        text = text[:index_l] + new + text[index_l + len(old):]
        idx = index_l + len(new) 
    return text