我是一名学习Python的人,正在研究如何使用字典来更好地进行字符串替换。
我有一个包含自定义占位符的字符串,如下所示:
placeholder_prefix = '$['
placeholder_suffix = ']'
dict={'key1':'string','key2':placeholders}
msg='This $[key1] contains custom $[key2]'
我希望占位符('prefix-suffix'和'keys')能够被下面字典中的'value'替换:
'This string contains custom placeholders' 通过编写以下函数,我可以获得消息:“这个[string]包含自定义[占位符]”:
def replace_all(text):
for key, value in brand_dictionary.iteritems():
text = text.replace(key, value).replace('$[', '[')
return text
我可以尝试不同的替换方式来移除"$["和"]",但这样会替换消息本身作为占位符的任何字符(比如"$","[","]")。所以我想避免这种情况,只替换自定义占位符。
我想到了正则表达式(用于占位符),但因为我的消息包含多个键,所以似乎不太有用?
在Python中有更好的方法吗?
'This {key1} contains custom {key2}'.format(**dict)
- Peter Wooddict
遮蔽了内置的dict
类型。 - Peter Wood