不区分大小写的替换

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



森栏
浏览 488回答 3
3回答

慕码人2483693

在一行中:import rere.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 rere.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'

至尊宝的传说

继续bFloch的回答,此功能将不改变任何一个,而是将所有旧出现的内容更改为新内容-以不区分大小写的方式。def ireplace(old, new, text):&nbsp; &nbsp; idx = 0&nbsp; &nbsp; while idx < len(text):&nbsp; &nbsp; &nbsp; &nbsp; index_l = text.lower().find(old.lower(), idx)&nbsp; &nbsp; &nbsp; &nbsp; if index_l == -1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return text&nbsp; &nbsp; &nbsp; &nbsp; text = text[:index_l] + new + text[index_l + len(old):]&nbsp; &nbsp; &nbsp; &nbsp; idx = index_l + len(new)&nbsp;&nbsp; &nbsp; return text
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python