Python String Template

Filed Under: Python String

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.

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.

  1. 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, then KeyError will be raised.
  2. 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.')

# dictionary as substitute argument
d = {"name": "Tim Cook", "job": "CEO", "company": "Apple Inc."}
s = t.substitute(**d)


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')

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')

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')

Output: Test adjective is Testing

You can checkout complete script and more Python string examples from our GitHub Repository.


Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors