如何用python中的目标字符串替换不区分大小写的字符串?

How to replace case insentive string in python, with the target string in?

我知道如何替换 python 中的字符串,但我只想在目标字符串不区分大小写的情况下在目标字符串周围添加一些标记。有什么简单的方法可以使用吗? 例如,我想在一些单词周围添加方括号,例如:

"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'()', 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'()', variants[2]))

#I have (APPLE) and (aPpLe).