文字列の複数の部分文字列を置換するにはどうすればいいですか? 質問する

文字列の複数の部分文字列を置換するにはどうすればいいですか? 質問する

.replace 関数を使用して複数の文字列を置き換えたいと思います。

私は現在

string.replace("condition1", "")

でも、次のようなものが欲しい

string.replace("condition1", "").replace("condition2", "text")

それは良い構文ではないように感じますが

これを実行する適切な方法は何ですか?grep / regexでフィールドを特定の検索文字列に置き換える方法\1と似ています\2

ベストアンサー1

正規表現を使用して目的を達成できる短い例を次に示します。

import re

rep = {"condition1": "", "condition2": "text"} # define desired replacements here

# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.items()) 
pattern = re.compile("|".join(rep.keys()))
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)

例えば:

>>> pattern.sub(lambda m: rep[re.escape(m.group(0))], "(condition1) and --condition2--")
'() and --text--'

おすすめ記事