What are Template Strings?

  • When were Template Strings introduced in Python?
  • How and when should one use Template Strings?

In Python 2.4, the Python Template class was added to the string module.

This class allows us to create simple syntax for output specification. In my opinion, the best time to use template strings is when you’re handling formatted strings generated by users of your program.

Following are some rules one needs to conform to while using Template class:

  • $ - The dollar symbol is used to support substitution/interpolation.
  • $$ - This is an Escape sequence for the single $ symbol.
  • $identifier - This is a substitution placeholder. An identifier is any sequence of upper and lower case letters A to Z, underscores (_), and digits 0 to 9. An identifier cannot begin with digits nor can it be a Python keyword.
  • ${identifier} - Equivalent to $identifier. It is used when valid characters appear after the placeholder but are not a part of the placeholder without any space between the two.
  • Any other appearance of $ will raise a ValueError.

Some examples of valid placeholders can be $name, $age20XX, $location_25 , ${noun}ification, etc.


Let us look at a couple of examples now:

Input:

from string import Template
name = 'Tanya'
place = 'Delhi, India'
string = Template( 'I am $name. I am from $place.')

The above code would not give us the string that we require. Here, we have only only created a string template and we need to use .substitute() method to print the desired string.

Input:

from string import Template
name = 'Tanya'
place = 'Delhi, India'
string_template = Template( 'I am $name. I am from $place.')
print(string_template.substitute(name = name, place = place))

Output:

I am Tanya. I am from Delhi, India.


Now, let us look at example which combines all the rules mentioned above.

Input:

from string import Template
name = 'Tanya'
username = 'tanyachawla'
amount = 10
string_template = Template( '${name}(@${username}) sent you $$$amount.')
print(string_template.substitute(name = name, amount = amount, username = username))

Output:

Tanya(@tanyachawla) sent you $10.

You can see the order in which arguments are called in .substitute() does not matter. Also, $$ shows that we do not necessarily need to add a space between escaped sign and next placeholder.


We can also use dictionaries:

Input:

from string import Template
dict = {'name' :'Tanya', 'username' :'tanyachawla', 'amount' :10}
string_template = Template( '${name}(@${username}) sent you $$$amount.')
print(string_template.substitute(**dict))

Output:

Tanya(@tanyachawla) sent you $10.


Now let us see what will happen if we do not provide a keyword argument for one of the placeholders.

Input:

from string import Template
name = 'Tanya'
place = 'Delhi, India'
string_template = Template( 'I am $name. I am from $place.')
print(string_template.substitute(name = name))

Output:

KeyError: 'place'

Python throws a KeyError as argument is not provided for $place in the above code. In such cases we use .safe_substitute() instead of .substitute().

.safe_substitute() does not throw the KeyError whereas the following would happen.

Input:

from string import Template
name = 'Tanya'
place = 'Delhi, India'
string_template = Template( 'I am $name. I am from $place.')
print(string_template.safe_substitute(name = name))

Output:

I am Tanya. I am from $place.



What differentiates Template from the rest of the string interpolation ways/tool available in Python, is that the type of the argument is not taken into account. Any type of object that can be converted into a string can be passed. The Template class will automatically convert these objects into strings and then insert them into the final string.

3 Likes