如何用python中的目标字符串替换python中不区分大小写的字符串?
我知道如何在python中替换字符串,但我只想在目标字符串不区分大小写时在目标字符串周围添加一些标记。有什么简单的方法可以用吗? 例如,我想在一些单词周围添加括号,如:如何用python中的目标字符串替换python中不区分大小写的字符串?,python,regex,string,case-insensitive,Python,Regex,String,Case Insensitive,我知道如何在python中替换字符串,但我只想在目标字符串不区分大小写时在目标字符串周围添加一些标记。有什么简单的方法可以用吗? 例如,我想在一些单词周围添加括号,如: "I have apple." -> "I have (apple)." "I have Apple." -> "I have (Apple)." "I have APPLE." -> "I have (APPLE)." 必须使匹配项不区分大小写。 您可以在模式中包括该标志,如中所示: impor
"I have apple." -> "I have (apple)."
"I have Apple." -> "I have (Apple)."
"I have APPLE." -> "I have (APPLE)."
必须使匹配项不区分大小写。 您可以在模式中包括该标志,如中所示:
import re
variants = ["I have apple.", "I have Apple.", "I have APPLE and aPpLe."]
def replace_apple_insensitive(s):
# Adding (?i) makes the matching case-insensitive
return re.sub(r'(?i)(apple)', r'(\1)', s)
for s in variants:
print(s, '-->', replace_apple_insensitive(s))
# I have apple. --> I have (apple).
# I have Apple. --> I have (Apple).
# I have APPLE and aPpLe. --> I have (APPLE) and (aPpLe).
或者,您可以编译正则表达式并将不区分大小写的标志保留在模式之外:
apple_regex = re.compile(r'(apple)', flags=re.IGNORECASE) # or re.I
print(apple_regex.sub(r'(\1)', variants[2]))
#I have (APPLE) and (aPpLe).
必须使匹配项不区分大小写。 您可以在模式中包括该标志,如中所示:
import re
variants = ["I have apple.", "I have Apple.", "I have APPLE and aPpLe."]
def replace_apple_insensitive(s):
# Adding (?i) makes the matching case-insensitive
return re.sub(r'(?i)(apple)', r'(\1)', s)
for s in variants:
print(s, '-->', replace_apple_insensitive(s))
# I have apple. --> I have (apple).
# I have Apple. --> I have (Apple).
# I have APPLE and aPpLe. --> I have (APPLE) and (aPpLe).
或者,您可以编译正则表达式并将不区分大小写的标志保留在模式之外:
apple_regex = re.compile(r'(apple)', flags=re.IGNORECASE) # or re.I
print(apple_regex.sub(r'(\1)', variants[2]))
#I have (APPLE) and (aPpLe).
请参阅
IGNORECASE
标志。请参阅IGNORECASE
标志。