简体   繁体   English

如何在Python中将MAP中的值替换为字符串模板

[英]How to substitute values in a MAP to string template in Python

I have a string with placeholders. 我有一个带占位符的字符串。 I want to substitute values for that placeholders and those values are stored in a MAP (dictionary). 我想用这些占位符替换值,并将这些值存储在MAP(字典)中。 I am using following code 我正在使用以下代码

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

This want give me correct results 这想给我正确的结果

My output should be: 我的输出应为:

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

Could you give me your opinion on how to do this ? 你能给我我的意见吗?

I would recommend using a template engine like Genshi . 我建议使用像Genshi这样的模板引擎。 This gives you more flexibility and well they are designed to do this :-) 这为您提供了更大的灵活性,并且它们被设计为可以做到这一点:-)

Genshi example based on http://genshi.edgewall.org/wiki/Documentation/0.6.x/templates.html : 基于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

It's also easy to create some markup by using genshi.template.MarkupTemplate . 使用genshi.template.MarkupTemplate创建标记也很容易。

I also recommend to separate the template from the code, you can use file-like objects for TextTemplate or MarkupTemplate . 我还建议将模板与代码分开,可以将类似文件的对象用于TextTemplateMarkupTemplate

You can just use string format for your example: 您可以使用字符串格式作为示例:

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM