不区分大小写的替换

2025-03-04 08:25:00
admin
原创
94
摘要:问题描述:在 Python 中进行不区分大小写的字符串替换的最简单方法是什么?解决方案 1:该string类型不支持此功能。您最好使用带有re.IGNORECASE选项的正则表达式子方法。>>> import re >>> insensitive_hippo = re.co...

问题描述:

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


解决方案 1:

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'

解决方案 2:

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

解决方案 3:

一行代码:

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'

解决方案 4:

继续 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

解决方案 5:

就像布莱尔康拉德所说的那样,string.replace 不支持此功能。

使用正则表达式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:Tempin', r'[BinFolder]    est.exe')
'C:\\Temp\\bin\\test.exe'

解决方案 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):] 

解决方案 7:

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

# 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)
'grassroot grassroot grassroot'

>>> re.sub(r'treeroot', 'grassroot', old)
'TREEROOT grassroot TREerOot'

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

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

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

为了比较:

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

>>> re.findall(r'treeroot', old)
['treeroot']

解决方案 8:

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

解决方案 9:

我正在将 \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 中测试

解决方案 10:

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

解决方案 11:

一行简单的解决方案,无需导入:-)

words = 'GREETINGS from EGYPT. GreeTings from Cairo'
replace_what, replace_with,  = 'Greetings', 'Hello'

result = ' '.join([replace_with if word.lower() == replace_what.lower() else word for word in words.split(' ')])
print (result)

结果是:

Hello from EGYPT. Hello from Cairo
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   4008  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   2751  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Freshdesk、ClickUp、nTask、Hubstaff、Plutio、Productive、Targa、Bonsai、Wrike。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在项目管理过程中面临着诸多痛点,如任务分配不...
项目管理系统   86  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Monday、TeamGantt、Filestage、Chanty、Visor、Smartsheet、Productive、Quire、Planview。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多项目经理和团队在管理复杂项目时,常...
开源项目管理工具   97  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Smartsheet、GanttPRO、Backlog、Visor、ResourceGuru、Productive、Xebrio、Hive、Quire。在当今快节奏的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在选择项目管理工具时常常面临困惑:...
项目管理系统   85  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用