在一个模板中格式化任意迭代

时间:2017-10-24 11:49:30

标签: python python-3.x string-formatting

是否可以使用Python 3.4的内置字符串格式化工具将任意迭代的项重复格式化为一个通用模板?

即。我想知道是否有一些魔法可以渲染单个字符串,如:

TEMPLATE = '''Hello {name},

 these are your items:

* {item for item in items}'''

使用string.format

OUTPUT = TEMPLATE.format(name='John Doe', items=['foo', 'bar', 123])

以便输出为:

Hello John Doe,

these are your items:

* foo
* bar
* 123

我知道我可以使用单个项目的单独模板来实现结果,然后将其渲染为上级格式字符串。但我想一步到位。

2 个答案:

答案 0 :(得分:1)

您可以将'\n* '.join(items)用于此目的,而不是第二个模板。我相信以下内容符合您的需求。

template = '''Hello {name},

These are your items:

* {items}
'''
formatted_text = template.format(name='sytech', 
                                 items='\n* '.join(['foo', 'bar', 'baz'])
)

print(formatted_text)

输出为

Hello sytech,

These are your items:

* foo
* bar
* baz

没有神奇的内置方法,您可以告诉str.format从列表中制作项目符号列表。但是,如果您指定'bullet'格式规范IE {items:bullet},则可以编写自己的自定义格式化程序来执行此操作。它与表格下面的内容大致相同,但每次都不需要明确地.join

from string import Formatter
class BulletFormatter(Formatter):
    def format_field(self, value, format_spec):
        if format_spec != 'bullet':
            return super().format_field(value, format_spec)
        return '* {}'.format('\n* '.join(value))

template = '''Hello {name},

These are your items:

{items:bullet}
'''

bullet_formatter = BulletFormatter()
output = bullet_formatter.format(template, name='sytech', items=['foo', 'bar', 'baz'])
print(output)

输出与上述相同。

除此之外,如果你想要更复杂的模板,Jinja可能是个不错的选择。这个jinja2模板可能看起来像

'''Hello {{ name }},
These are your items:

{% for item in items %}
* {{ item }}
{% endfor %}
'''

答案 1 :(得分:1)

我建议您使用Jinja2模板来处理这个用例 - 它非常快,并且很多人都使用它。

有关详细信息,请参阅http://jinja.pocoo.org