不区分大小写的替换

问题描述 投票:141回答:9

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

python string case-insensitive
9个回答
193
投票

string类型不支持此功能。你可能最好使用the regular expression sub methodre.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'

70
投票
import re
pattern = re.compile("hello", re.IGNORECASE)
pattern.sub("bye", "hello HeLLo HELLO")
# 'bye bye bye'

35
投票

在一行中:

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'

10
投票

继续bFloch的回答,这个函数将改变不是一个,而是所有出现的旧的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

2
投票

这不需要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):] 

2
投票

就像Blair Conrad说的那样string.replace不支持这个。

使用正则表达式re.sub,但请记住首先逃避替换字符串。请注意,re.sub在2.6中没有标记选项,因此您必须使用嵌入式修饰符'(?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'

1
投票

此函数使用str.replace()re.findall()函数。它将用pattern以不区分大小写的方式替换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

0
投票

从来没有发过一个答案,而且这个帖子真的很老但是我想出了另一个解决方案,并且认为我可以得到你的责任,我没有经验丰富的Python编程,所以如果有它的外观缺点,请指出它们,因为它的良好学习: )

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))

0
投票

我没有被转换为escape sequences(向下滚动),所以我注意到re.sub将反向转义的转义字符转换为转义序列。

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

替换不区分大小写。

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

此外,如果你想用转义字符替换它,就像这里得到转换为转义序列的特殊含义bashslash字符的其他答案一样,只需解码你的find,或者替换字符串。在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中测试

希望有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.