Python Template Strings

Python’s Template String Class provides a way for simple string substitution, wherein the template fields are substituted with suitable replacement strings provided by the user.

Sometimes, it may be a preference to have an easier to replace string, rather than using other format strings for substitution. Template Strings are used exactly for this purpose, to easily replace strings with minimum hassles and without exceptions.


String Template Rules

Template Strings support $ based substitutions, which conform to the following rules :

  • $$ -> This is an Escape sequence for the single $ symbol, since it would be classified as a modifier otherwise.
  • $identifier -> This is a Substitution placeholder.
  • ${identifier} -> Equivalent to $identifier. Is used when valid characters appear after the placeholder but are not a part of the placeholder.
  • Any other appearance of $ will raise a ValueError Exception.

Here is an example to demonstrate basic Template Substitution:

from string import Template

# Create a template with 'name' as the placeholder
template = Template('Hello $name!')

student = 'Amit'

# Perform the template substitution and print the result
print(template.substitute(name=student))

Output

Hello Amit!

Here is another snippet to demonstrate the other rules of Template Substitution:

from string import Template

# Create a template with $CODE as the placeholder
# The $$ is to escape the dollar sign
template = Template('The generated Code is ${CODE}-$$100')

code = 'H875'

# Perform the template substitution and print the result
print(template.substitute(CODE=code))

Output

The generated Code is H875-$100

String Template Class methods

1. The Template Constructor

We have already encountered this in our earlier snipper, where we create our string template object using Template(template_string).

Format: template_object = Template(template_string)

2. substitute(mapping, **kwargs)

This is also a part of our earlier snippet, which performs a template substitution from mapping to the keyword arguments kwargs.

The second argument is a **kwargs because we pass keyword arguments as placeholders for substitution. Therefore, it is passed as a Dictionary for template substitution.

To illustrate this point, we show how to pass a dictionary into the template string.

from string import Template

template = Template('The shares of $company have $state. This is $reaction.')

# Perform the template substitution and print the result
print(template.substitute(state = 'dropped', company='Google', reaction='bad'))

# Perform substitution by passing a Dictionary
dct = {'state': 'risen', 'company': 'Apple', 'reaction': 'good'}

print(template.substitute(**dct))

# Incomplete substitution results in a KeyError
try:
    template.substitute(state = 'dropped')
except KeyError:
    print('Incomplete substitution resulted in KeyError!')

Output

The shares of Google have dropped. This is bad.
The shares of Apple have risen. This is good.
Incomplete substitution resulted in KeyError!

3. safe_substitute(mapping, **kwargs)

This is similar to substitute(), except that if placeholders are missing from mapping and kwargs, instead of raising a KeyError exception, the original placeholder will appear in the resulting string intact.

from string import Template

template = Template('The shares of $company have $state. This is $reaction.')

print(template.safe_substitute(company='Google'))

Output

The shares of Google have $state. This is $reaction.

As you can see, there is no KeyError, resulting in an incomplete, but error-free substitution. This is why the substitution is ‘safe’.


Template Class attributes

The Template object has the template attribute, which returns the template string. Although it can be modified, it is good practice to not change this attribute value.

from string import Template

t = Template('Hello $name, are you $cond?')
print(t.template)

Output

Hello $name, are you $cond?

Conclusion

In this article, we learned about the String Template Class, and some of it’s methods for regular and safe substitution of template strings. We also saw how we could use them for simple and easy string substitution.


References