在Python中进行不区分大小写的字符串替换最简单的方法是什么?
发布于 2009-05-28 03:39:14
string
类型不支持这一点。最好使用带有re.IGNORECASE选项的the regular expression sub method。
>>> 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'
发布于 2009-05-28 03:41:05
import re
pattern = re.compile("hello", re.IGNORECASE)
pattern.sub("bye", "hello HeLLo HELLO")
# 'bye bye bye'
发布于 2012-03-15 04:14:04
在一行中:
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'
或者,使用可选的“flag”参数:
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'
https://stackoverflow.com/questions/919056
复制相似问题