在Python中做不区分大小写的字符串替换最简单的方法是什么?
当前回答
继续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
其他回答
在一行中:
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'
关于语法细节和选项的有趣观察:
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)
[“树根”]
继续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
字符串类型不支持这一点。你可能最好使用正则表达式子方法和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'
我有\t被转换为转义序列(向下滚动一点),所以我注意到re.sub将反切转义字符转换为转义序列。
为了防止这种情况的发生,我写了以下内容:
替换不区分大小写。
import re
def ireplace(findtxt, replacetxt, data):
return replacetxt.join( re.compile(findtxt, flags=re.I).split(data) )
同样,如果你想用转义字符替换它,就像这里的其他答案一样,将特殊含义的bashslash字符转换为转义序列,只需解码你的find and或replace字符串。在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中测试
推荐文章
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本
- 我在哪里调用Keras的BatchNormalization函数?
- 打印测试执行时间并使用py.test锁定缓慢的测试
- 插入一行到熊猫数据框架
- 我如何在Swift连接字符串?
- 要列出Pandas DataFrame列
- 在Django模型中存储电话号码的最佳方法是什么?
- 从导入的模块中模拟函数
- 滚动或滑动窗口迭代器?
- python的方法找到最大值和它的索引在一个列表?
- 如何获得一个变量值,如果变量名存储为字符串?
- 如何读取文件的前N行?
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?
- 如何删除matplotlib中的顶部和右侧轴?