pythonpython-3.xpython-2.7

Render lists using python Template string clases


I want to use a Template string class starting from a list. I started with:

from string import Template
temp = Template('-* $item - \n')
items = ["alpha", "beta", "gama"]
subs = ''.join([temp.substitute(item) for item in items])

This fails because it needs a dictionary and not a list.

Results should be:

-* alpha -
-* beta -
-* gama -

Some limitations:


Solution

  • substitute needs to know what the $item placeholder in the template should be replaced with, so either provide a mapping dictionary:

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

    Or, as @Rfroes87 mentioned in the comment, pass item as a kwarg:

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