I am looking for either technique or templating system for Python for formatting output to simple text. What I require is that it will be able to iterate through multiple lists or dicts. It would be nice if I would be able to define template into separate file (like output.templ) instead of hardcoding it into source code.
As simple example what I want to achieve, we have variables title
, subtitle
and list
title = 'foo' subtitle = 'bar' list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
And running throught a template, output would look like this:
Foo Bar Monday Tuesday Wednesday Thursday Friday Saturday Sunday
How to do this? Thank you.
In python, template is a class of String module. It allows for data to change without having to edit the application. It can be modified with subclasses. Templates provide simpler string substitutions as described in PEP 292.
Templating, and in particular web templating is a way to represent data in different forms. These forms often (but not always) intended to be readable, even attractive, to a human audience. Frequently, templating solutions involve a document (the template) and data.
You can use the standard library string an its Template class.
Having a file foo.txt
:
$title $subtitle $list
And the processing of the file (example.py
):
from string import Template d = { 'title': 'This is the title', 'subtitle': 'And this is the subtitle', 'list': '\n'.join(['first', 'second', 'third']) } with open('foo.txt', 'r') as f: src = Template(f.read()) result = src.substitute(d) print(result)
Then run it:
$ python example.py This is the title And this is the subtitle first second third
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With