在Python中做不区分大小写的字符串替换最简单的方法是什么?
当前回答
这个函数同时使用str.replace()和re.findall()函数。 它将以不区分大小写的方式将字符串中出现的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
其他回答
在一行中:
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'
字符串类型不支持这一点。你可能最好使用正则表达式子方法和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'
继续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
关于语法细节和选项的有趣观察:
win32上的Python 3.7.2 (tags/v3.7.2:9a3ffc0492, december 23 2018, 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)
" TREEROOT grassroot TREEROOT "
re.sub(r'treeroot', 'grassroot', old, flags=re.I)
草根的,草根的
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)
[“树根”]
import re
pattern = re.compile("hello", re.IGNORECASE)
pattern.sub("bye", "hello HeLLo HELLO")
# 'bye bye bye'
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- Printf与std::字符串?
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if