Learn Python - Python tutorial - python string template - Python examples - Python programs
In String module, Template Class allows us to create simplified syntax for output specification. The format uses placeholder names formed by $ with valid Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with braces allows it to be followed by more alphanumeric letters with no intervening spaces. Writing $$ creates a single escaped $:
Below is a simple example.
python tutorial - Output :
Following is another example where we import names and marks of students from a list and print them using template.
python - Sample - python code :
python tutorial - Output :
The substitute() method raises a KeyError when a placeholder is not supplied in a dictionary or a keyword argument. For mail-merge style applications, user supplied data may be incomplete and the safe_substitute() method may be more appropriate — it will leave placeholders unchanged if data is missing:
Another application for template is separating program logic from the details of multiple output formats. This makes it possible to substitute custom templates for XML files, plain text reports, and HTML web reports.
Note that there are other ways also to print formatted output like %d for integer, %f for float, etc.,