Python String Template class is used to create a simple template string, where fields can be replaced later on to create a string object. We can use string format() function to create a string too. However, format() function provides a lot of options and in some situations, we want the simple replacement features, for example, Internationalization (i18n). In these cases, template string is useful and easy to use.
Table of Contents
Python String Template
Python String Template is created by passing template string to its constructor. Python template strings support $-based substitutions.
Template class has two functions to create a string from the template.
- substitute(mapping, **kwds): performs substitution from the dictionary like key based mapping object or from the keyword arguments. If both mapping and keyword arguments have same key, then TypeError is thrown. The error message will look like
TypeError: substitute() got multiple values for keyword argument 'aaa'
. If the key is not provided, thenKeyError
will be raised. - safe_substitute(mapping, **kwds): behaves just like substitue() method, except when key is not found then it doesn’t raise KeyError and placeholder is returned in the result string.
Python Template String Example
Let’s look at simple example of template string in python.
from string import Template
t = Template('$name is the $job of $company')
s = t.substitute(name='Tim Cook', job='CEO', company='Apple Inc.')
print(s)
# dictionary as substitute argument
d = {"name": "Tim Cook", "job": "CEO", "company": "Apple Inc."}
s = t.substitute(**d)
print(s)
Output:
Tim Cook is the CEO of Apple Inc.
Tim Cook is the CEO of Apple Inc.
safe_substitute() example
from string import Template
t = Template('$name is the $job of $company')
s = t.safe_substitute(name='Tim Cook', job='CEO')
print(s)
Output: Tim Cook is the CEO of $company
Printing template string
Template object has “template” attribute that returns the template string.
t = Template('$name is the $job of $company')
print('Template String =', t.template)
Output: Template String = $name is the $job of $company
Escaping $ sign
We can use $$ to escape $ sign and treat it as part of normal string.
t = Template('$$ is called $name')
s = t.substitute(name='Dollar')
print(s)
Output: $ is called Dollar
${identifier} example
${identifier} is same as $identifier. It’s required when valid identifier characters follow the placeholder but are not part of the placeholder. Let’s understand this with a simple example.
t = Template('$noun adjective is ${noun}ing')
s = t.substitute(noun='Test')
print(s)
Output: Test adjective is Testing