使用字典进行字符串替换

8

我是一名学习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中有更好的方法吗?


2
这是你必须用这种方式解决的某种类型的作业吗?还是你不能只是利用“格式”呢?(https://docs.python.org/2/library/string.html#format-string-syntax) - fditz
1
'This {key1} contains custom {key2}'.format(**dict) - Peter Wood
dict 遮蔽了内置的 dict 类型。 - Peter Wood
我需要自定义占位符(用于定制品牌目的的消息中的某些部分)。格式对于%s有效,我知道它与字典一起很好地工作。 - akhi
5个回答

4

试试这个:

dict={key1:'string',key2:placeholders}

msg='This {key1} contains custom {key2}'.format(**dict)

例如,我执行的命令:

>>> msg="hello {a} {b}"
>>> t={"a":"aa","b":"bb"}
>>> msg="hello {a} {b}".format(**t)
>>> msg
'hello aa bb'

1
键1和键2不需要是字符串吗? - Anand S Kumar
1
dict={'key1':'字符串','key2':'占位符'} msg='这个 {key1} 包含自定义的 {key2}'.format(**dict) - Avinash Garg

2
作为一种更通用的方法,您可以使用re.sub和适当的替换函数:
>>> d={'key1':'string','key2':'placeholders'}
>>> re.sub(r'\$\[([^\]]*)\]',lambda x:d.get(x.group(1)),msg)
'This string contains custom placeholders'

使用正则表达式的好处在于,它会拒绝匹配不符合预期格式的字符串中的占位符字符!
或者,您可以使用以下简单的字符串格式化方式:
In [123]: d={'key1':'string','key2':'placeholders'}
     ...: msg='This {key1} contains custom {key2}'
     ...: 
     ...: 

In [124]: msg.format(**d)
Out[124]: 'This string contains custom placeholders'

如果你的变量数量不是很大,可以使用当前命名空间中可访问的变量作为键,而不是使用字典。然后可以使用自 Python-3.6 版本引入的 f-strings 功能:

In [125]: key1='string'
     ...: key2= 'placeholders'
     ...: msg=f'This {key1} contains custom {key2}'
     ...: 

In [126]: msg
Out[126]: 'This string contains custom placeholders'

太完美了!这正是我想要的。谢谢 Kasra。 - akhi
1
有些人在面对问题时,会想:「我知道,我用正则表达式来解决。」现在他们有两个问题了。- Jamie Zawinski ;) - Steven Correia
我尝试使用相同的正则表达式,但不知道“lambda”表达式及其有用性。你可以解决一个问题,但总有最好的解决方案!在这种情况下,我从Kasra那里得到了最佳解决方案 :-) - akhi

2

另一种选项是使用字符串替换进行格式化:

msg='This %(key1)s contains custom %(key2)s'
dict={'key1':'string','key2':'placeholders'}
print(msg%dict)

>> This string contains custom placeholders

1
如果您可以更改占位符,您可以使用%(key)s%运算符在这些位置自动应用字典。
例如 -
>>> dict={'key1':'string','key2':'placeholders'}
>>> msg='This %(key1)s contains custom %(key2)s'
>>> print(msg%dict)
This string contains custom placeholders

-1

不要自己造轮子,考虑使用现有的模板库,比如 Mako (http://www.makotemplates.org/)。

它们已经实现了你想要的一切,还有很多你还没有想到的功能。

(是的,它们也适用于生成非 HTML 文本)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接