2017-04-15 22 views
0

私はPythonで文字列を置き換える方法を知っていますが、ターゲット文字列が大文字小文字を区別している間に、ターゲット文字列の周りにいくつかのマークを追加したいだけです。私が使うことができる簡単な方法はありますか?あなたがマッチングは大文字と小文字を区別しないしなければならない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). 
関連する問題