使用python模板字符串类别呈现列表

使用python模板字符串类别呈现列表,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,我想使用一个从列表开始的模板字符串类。我从以下几点开始: from string import Template temp = Template('-* $item - \n') items = ["alpha", "beta", "gama"] subs = ''.join([temp.substitute(item) for item in items]) 这失败了,因为它需要字典而不是列表 结果应该是: -* alpha - -

我想使用一个从列表开始的模板字符串类。我从以下几点开始:

from string import Template
temp = Template('-* $item - \n')
items = ["alpha", "beta", "gama"]
subs = ''.join([temp.substitute(item) for item in items])
这失败了,因为它需要字典而不是列表

结果应该是:

-* alpha -
-* beta -
-* gama -
一些限制:

我知道可以使用append完成,但我希望传递模板的灵活性,其中一些模板比示例中的模板更复杂 应该与python2和pytho3一起使用 理想情况下,将更像jinja2或django模板呈现,但不幸的是,我不能添加第三方包,此外,我只需要变量和列表替换。 substitute需要知道模板中的$item占位符应替换为什么,因此提供映射字典:

subs = ''.join([temp.substitute({'item': item}) for item in items])
或者,如注释中提到的@Rfroes87,将项作为kwarg传递:

subs = ''.join([temp.substitute(item=item) for item in items])

尝试使用字符串格式而不是模板,它甚至可能有相同的后台引擎

subs = ''.join(['-* %s - \n' % item for item in items])

也可以将kwargs与替换一起使用,将其简化为temp.substituteitem=项。@Rfroes87谢谢,将在2.7.5中将其作为选项添加。