Use Python's Built-In Template Strings To Generate Output
March - 2022
Python ships with built-in functionality for generating output from templates that provide basic variable replacement.
From A String
from string import Template
skeleton = Template('Name: $name - Color: $color')
output = skeleton.substitute(
name="Karl",
color="Green"
)
print(output)
Produces:
Name: Karl - Color: Green
From A File
Assuming you have a files named template.txt
with:
this is the name: $name
and the color: $color
Then this:
from string import Template
with open('template.txt') as _tmpl:
frame = Template(_tmpl.read())
output = frame.substitute(
name="Karl",
color="Green"
)
print(output)
Will produce:
this is the name: Karl
and the color: Green
Reference
docs: https://docs.python.org/3/library/string.html#template-strings