2017-04-15 61 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). 
相關問題