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


当前回答

字符串类型不支持这一点。你可能最好使用正则表达式子方法和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'

其他回答

这并不需要RegularExp

def ireplace(old, new, text):
    """ 
    Replace case insensitive
    Raises ValueError if string not found
    """
    index_l = text.lower().index(old.lower())
    return text[:index_l] + new + text[index_l + len(old):] 

字符串类型不支持这一点。你可能最好使用正则表达式子方法和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

在一行中:

import re
re.sub("(?i)hello","bye", "hello HeLLo HELLO") #'bye bye bye'
re.sub("(?i)he\.llo","bye", "he.llo He.LLo HE.LLO") #'bye bye bye'

或者,使用可选的"flags"参数:

import re
re.sub("hello", "bye", "hello HeLLo HELLO", flags=re.I) #'bye bye bye'
re.sub("he\.llo", "bye", "he.llo He.LLo HE.LLO", flags=re.I) #'bye bye bye'

就像布莱尔·康拉德说的那样Replace不支持此功能。

使用正则表达式re.sub,但记得先转义替换字符串。注意,在2.6中re.sub没有标记选项,所以你必须使用嵌入的修饰符'(?i)'(或一个RE-object,参见Blair Conrad的回答)。另外,另一个缺陷是,如果给出了字符串,sub将在替换文本中处理反斜杠转义。为了避免这种情况,可以改为传入lambda。

这是一个函数:

import re
def ireplace(old, repl, text):
    return re.sub('(?i)'+re.escape(old), lambda m: repl, text)

>>> ireplace('hippo?', 'giraffe!?', 'You want a hiPPO?')
'You want a giraffe!?'
>>> ireplace(r'[binfolder]', r'C:\Temp\bin', r'[BinFolder]\test.exe')
'C:\\Temp\\bin\\test.exe'