2017-04-15 62 views
0

我知道如何替换python中的字符串,但我只想在目标字符串周围添加一些标记,而目标字符串是caseinsentive。有什么简单的方法可以使用吗? 例如,我想添加支架周围的一些话,如:如何在python中替换大小写字符串,目标字符串在?

"I have apple." -> "I have (apple)." 
"I have Apple." -> "I have (Apple)." 
"I have APPLE." -> "I have (APPLE)." 
+1

见'IGNORECASE'标志。 https://docs.python.org/2/howto/regex.html#compilation-flags –

回答

2

您必须匹配不区分大小写。 您可以在模式中包含的标志,如:

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). 
相关问题