Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 不区分大小写的替换_Python_String_Case Insensitive - Fatal编程技术网

Python 不区分大小写的替换

Python 不区分大小写的替换,python,string,case-insensitive,Python,String,Case Insensitive,Python中不区分大小写的字符串替换最简单的方法是什么?字符串类型不支持这种方法。您最好使用该选项 这不需要RegularExp def ireplace(old, new, text): """ Replace case insensitive Raises ValueError if string not found """ index_l = text.lower().index(old.lower()) return text[:ind

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

字符串类型不支持这种方法。您最好使用该选项


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

继续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
def-ireplace(旧、新、文本):
idx=0
当idx
以前从未发布过答案,而且这个帖子很老,但我提出了另一个解决方案,我想我可以得到你的回答,我对Python编程不熟悉,所以如果它有明显的缺点,请指出它们,因为它有很好的学习效果:)

在一行中:

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'

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

使用regex
re.sub
,但请记住首先转义替换字符串。请注意,2.6中没有针对
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'

我正在将\t转换为(向下滚动一点),因此我注意到将反斜杠转义字符转换为转义序列

为了避免这种情况,我写了以下内容:

替换为不区分大小写

import re
    def ireplace(findtxt, replacetxt, data):
        return replacetxt.join(  re.compile(findtxt, flags=re.I).split(data)  )
另外,如果您想将其替换为转义字符,就像这里的其他答案一样,将特殊含义的斜杠字符转换为转义序列,只需解码您的find and或replace字符串。在python3中,可能需要执行.decode(“unicode_escape”)#python3之类的操作

在Python 2.7.8中测试


希望对您有所帮助。

此函数同时使用
str.replace()
re.findall()
函数。 它将以不区分大小写的方式将
string
中出现的所有
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

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

win32上的Python 3.7.2(tags/v3.7.2:9A3FFC049220018年12月23日23:09:28)[MSC v.1916 64位(AMD64)]

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, re.I)
“树丛草根树丛”

re.sub(r'treeroot', 'grassroot', old, flags=re.I)
“草根草根”

re.sub(r'treeroot', 'grassroot', old)
re.sub(r'treeroot', 'grassroot', old, re.I)
“树丛草根树丛”

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

作为比较

re.findall(r'treeroot', old, re.I)
['TREEROOT'、'TREEROOT'、'TREEROOT']

re.findall(r'treeroot', old)

['treeroot']

好的一个,但是这不会改变所有出现的新旧版本,只会改变第一个出现的版本。它的可读性不如正则表达式版本。不需要在这里重新发明轮子。在这个版本和升级版本之间做一个性能比较会很有趣,它可能更快,这对一些应用程序很重要。或者它可能会慢一些,因为它在解释Python中做了更多的工作。如果您只进行一次替换,或者希望保存代码行,那么使用re.sub和(?i)标志re.sub(“(?i)+re.escape('hippo'),'giraffe','i want hippo for my birth')进行一次替换会更有效,为什么只对字符串使用re.escape?谢谢。@Elena,
'hippo'
不需要它,但是如果to replace值被传递到函数中,它会很有用,因此它确实是一个比其他任何东西都好的例子。除了必须
重新逃脱你的针之外,这里还有另一个陷阱,这个答案无法避免,注意:由于
re.sub
处理转义序列,如中所述,您需要转义替换字符串中的所有反斜杠或使用lambda。这不适用于将
r'a\BC'
替换为
r'D\EF'
中的
r'xxxA\BCxxx'
,正确答案是blow,johvFor learning中的一个:通常,当您对字符串进行搜索和替换时,最好不要首先将其转换为数组。这就是为什么第一个答案可能是最好的。当它使用外部模块时,它将字符串视为一个完整的字符串。对于学习来说:对于一个没有上下文的开发人员来说,阅读这段代码并理解它在做什么是非常困难的:)做得很好。比正则表达式好得多;它处理各种字符,而正则表达式对任何非字母数字的字符都非常挑剔。首选答案IMHO。你所要做的就是转义正则表达式:接受的答案比这个要短得多,更容易阅读。转义仅适用于匹配,目标中的反斜杠可能会把事情搞砸。或者一行:
re.sub('hello','bye','hello hello',flags=re.IGNORECASE)
请注意,
re.sub
仅支持此标志,因为Python 2.7。请确保您的答案优于此问题中已有的其他答案。从it 5个参数中:
re.sub(pattern,repl,string,count=0,flags=0)
这就是为什么
flags=re.I
有效,但尝试将其作为位置参数传递失败的原因,它位于错误的位置。
re.findall(r'treeroot', old)