如何在Python中替换映射到字符串模板中的值

2024-04-20 05:06:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带占位符的字符串。我想替换占位符的值,这些值存储在地图(字典)中。我使用以下代码

from string import Template

values = {'what': 'surreal', 'punctuation': 'is'}
t = Template(" Hello, $what world $punctuation One of Python least-used functions is ")
t.substitute(values)

print t

你想给我正确的结果吗

我的输出应该是:

Hello, surreal world is One of Python least-used functions is

你能告诉我你对如何做这件事的看法吗?你知道吗


Tags: of字符串helloworldis地图templatefunctions
2条回答

我建议使用Genshi这样的模板引擎。 这给了您更多的灵活性,而且它们的设计初衷是:-)

基于http://genshi.edgewall.org/wiki/Documentation/0.6.x/templates.html的Genshi示例:

>>> from genshi.template import TextTemplate
>>> tmpl = TextTemplate('Hello, ${dict.what} world ${dict.punctuation} One of Python least-used functions is')
>>> stream = tmpl.generate(dict={'what':'surreal', 'punctuation':'is'})
>>> print(stream)
Hello, surreal world is One of Python least-used functions is

使用genshi.template.MarkupTemplate创建一些标记也很容易。你知道吗

我还建议将模板与代码分开,您可以对TextTemplateMarkupTemplate使用类似文件的对象。你知道吗

您可以使用string format作为示例:

values = {'what': 'surreal', 'punctuation': 'is'}
template=" Hello, {what} world {punctuation} One of Python least-used functions is "
t = template.format(**values)
print(t)
# Hello, surreal world is One of Python least-used functions is 

相关问题 更多 >