How to Use Template Strings in Python

The aim of this page📝 is to define steps for simple use of Python template strings. My real-life usecase is a population of various configuration files in JSON format. This doc contains only a simple illustration.

Pavol Kutaj
2 min readOct 11, 2022

The primitive example of a template usage and its population would be something like

from string import Template
t = Template('Hey, $name!')
name = "Bob"
t.substitute(name=name)
'Hey, Bob!'

Template strings are not a core language feature but they’re supplied by the string module in the standard library. In essence, you need to 1) import Template function → 2) create Template object containing a variable to be populated → 3) populate the template with substitute() method.

The cool thing is that this is all built-in, so no need to worry about ensuring that everyone has a pip module imported.

STEPS

  • import the Template class from Python’s built-in string module.
# populate_template.py

from string import Template
  • create template → use python f-string syntax in a json
/* customer_tpl.json */

{
"customer": {
"address": "${address}"
}
}
  • to get the template, load a .json file and initialize Template class with
# populate_template.py
with open(f"customer_tpl.json") as json_tpl:
return Template(json_tpl.read())
  • get the value you need to populate the template with
  • run substitute() on a template object
# populate_template.py
address = input("street and house nr: ")
customer_object = customer_object_template.substitute(address=address)
return customer_object
  • remember, you still have a <string> object; you need json module to cast that string into the dictionary if you need any programmatic work
  • in the substitute(), I am employing a weird identity between parameter and argument value, similar to what has been applied in the template itself
  • this is a purely conventional matter of taste, you may argue it is a bit confusing to use the same identifiers for different levels of abstraction
  • also, logically, you need to use keyword arguments, where the keyword is the name of the variable in the f-string in the template and the argument holds the value you want to populate the template with

LINKS

--

--

No responses yet