Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用python中的目标字符串替换python中不区分大小写的字符串?_Python_Regex_String_Case Insensitive - Fatal编程技术网

如何用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

我知道如何在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'(\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
标志。