217

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

4

10 回答 10

255

string类型不支持此功能。您可能最好使用带有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'
于 2009-05-28T03:39:13.607 回答
100
import re
pattern = re.compile("hello", re.IGNORECASE)
pattern.sub("bye", "hello HeLLo HELLO")
# 'bye bye bye'
于 2009-05-28T03:41:04.857 回答
55

在一行中:

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'

或者,使用可选的“标志”参数:

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'
于 2012-03-14T20:14:03.707 回答
21

继续 bFloch 的回答,这个函数不会改变一个,而是所有出现的 old 和 new - 以不区分大小写的方式。

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
于 2011-01-23T11:46:46.397 回答
6

这不需要 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):] 
于 2011-01-21T14:09:54.507 回答
6

就像布莱尔康拉德说 string.replace 不支持这一点。

使用正则表达式re.sub,但请记住先转义替换字符串。请注意,2.6 中没有 flags-option for re.sub,因此您必须使用嵌入式修饰符'(?i)'(或 RE 对象,请参阅 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'
于 2013-04-05T10:03:57.463 回答
5

此函数同时使用str.replace()re.findall()函数。它将以不区分大小写的方式替换所有出现的patternin 。stringrepl

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
于 2019-04-16T20:17:06.260 回答
5

关于语法细节和选项的有趣观察:

Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32

import re
old = "TREEROOT treeroot TREerOot"
re.sub(r'(?i)treeroot', 'grassroot', old)

《草根草根草根》

re.sub(r'treeroot', 'grassroot', old)

'树根草根树根'

re.sub(r'treeroot', 'grassroot', old, flags=re.I)

《草根草根草根》

re.sub(r'treeroot', 'grassroot', old, re.I)

'树根草根树根'

因此,匹配表达式中的 (?i) 前缀或添加“flags=re.I”作为第四个参数将导致不区分大小写的匹配。但是,仅使用“re.I”作为第四个参数不会导致不区分大小写的匹配。

为了比较,

re.findall(r'treeroot', old, re.I)

['树根','树根','树根']

re.findall(r'treeroot', old)

['树根']

于 2020-01-20T04:14:20.153 回答
1

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

为了防止我写了以下内容:

替换不区分大小写。

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

此外,如果您希望它用转义字符替换,就像这里的其他答案将特殊含义的 bashslash 字符转换为转义序列一样,只需解码您的查找和或替换字符串。在 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 中测试

于 2014-10-28T03:18:39.047 回答
0
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))
于 2012-02-16T13:59:28.457 回答