Python string Template

Python string Template

Python string : Template class

This article demonstrate how to use Template class in string module.
This class is used to create a string template for simpler string substitutions . It's useful in implementing internationalization (i18n) in an application where we don't need complex formatting rules.

In general term : A template is a file that serves as a starting point for a new document. When you open a template, it is pre-formatted in some way.

What Is Template ?

  • In python, template is a class of String module.
  • It allows for data to change without having to edit the application.
  • It can be modified with subclasses.
  • Templates provide simpler string substitutions as described in PEP 292.
  • Templates substitution is "$" -based substitutions, rather than "%"-based substitutions

How It Works ?

  • Template class takes a string as a template, within the string use placeholder variable name with preceding the Dollar($) sign to depict there is the placeholder.
  • Then substitute value into the template with substitute() method using a dictionary. Where key is in the dictionary match with placeholder name. The returned string is the template  with all the values rather than the placeholder
  • It should also be noted that, the placeholder variable name should also be follow the same naming convention as variable naming in python.

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.

Substitution Rules For Python :

For performing substitution we should have to follow the following rules 

  • "$$" is an escape ; it is replaced with a single "$".
  • "$identifier" names a substitution placeholder matching a mapping key of "identifier" . By default, "identifier" must spell a Python identifier. The first non-identifier character after the "$" character terminates this placeholder specification.
  • "${identifier}is equivalent to"$identifier" . It is required when valid identifier characters follow the placeholder but are not part of the placeholder, such as "{noun}identification"

How To Implement Template ?

Now we will define a template and see how it works. So write the following codes for implementing template

#importing Template class fronm string module
from string import Template

#template creation
my_template = Template('My Name is $x')

print (my_template.substitute({'x' : "Vishal"}))

Output : My Name is Vishal

  • First of all import Template class from string module.
  • Then create a template that has placeholder for value of x.
  • And finally Substitute value of x in above template.

Sample code : substitute method

from string import Template

t = Template(' $name is working in $company')
s = t.substitute(name='Vishal'company='cppsecrets')

# dictionary as substitute argument
d = {"name""Vishal""company""cppsecrets."}
s = t.substitute(**d)

Output :
Vishal is working in cppsecrets 
Vishal is working in cppsecrets.

Sample code : safe_substitute() method

from string import Template

t = Template('$name is the $job at $company' )

s = t.safe_substitute(name='Vishal Lodhi'job='python developer'company='cppsecrets')

Output :
Vishal Lodhi is the python developer at cppsecrets

Printing template string :

Template object has "template" attribute that returns the template string.

from string import Template

t = Template('$name is the $job at $company')
print('Template String =', t.template)
Output :
Template String = $name is the $job at $company 

Escaping $ sign :

We can use $$ to escape $ sign and treat it as part of normal string.

from string import Template

t = Template('$$ is called $name')
s = t.substitute(name='Dollar')
Output :
$ is called Dollar

${identifier} :

${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.

from string import Template

t = Template(' $noun adjective is ${noun}ing')
s = t.substitute(noun='Test')

Output :
Test adjective is Testing

Template Errors :

Now we will see about template errors.  Template Errors have two types :

  1. Key Error : In a Key error, the template was not given a value for a placeholder. It means No Placeholder Match. 
  2. Value Error : In a Value error, the placeholder started with an invalid character(usually a number). It means Bad Placeholder. 

Handling Template Errors :

  • For handling these errors, template provide a safe_subsitute() method  and still give us back a string.
  • safe_subsitute() method will leave placeholders unchanged if data is missing,
  • You also get the placeholders in the returned string if there is an error with it.

Custom Delimiters :

  • You can also set a custom delimiter for the placeholder variables by overriding the Template class.
  • Let's change our delimiter to the Hash symbol(#). 
  • And now we will edit our previous example i.e., data output program.
  • Here we will use # rather than $.
from string import Template

# override the Template class
class MyTemplate(Template):
    delimiter = "#"

def Main():
    cart = []


# call the subclass of template
# this will substitute the value using # delimiter 
    cart_template = MyTemplate("#qty x #item = #price"
    total = 0
    print("My Cart :")

    for cart_data in cart:
        total += cart_data["price"]
    print("Total Price : " + str(total))

if __name__ == '__main__':
Output :
2 x Laptop = 900
10 x Tables = 50
Total Price : 1140

  • First of all create a subclass and override the base class.
  • Declare a delimiter, the delimiter should be #.
  • And then change the template, now in template we will use # instead of $.
  • So let's see what is the result of using custom delimiters.

Why Use Custom Templates ?

So now the question is that why use custom templates. So answer is below 

  • It saves typing and reduces code size.
  • Easy to implement custom templates from command line.
  • For eg.  MyPhoto_ = MyPhoto_0.jpg, MyPhoto_1.jpg etc.
  • Custom templates are extremely useful for webpages, as a webpage generally always follows the same template but with different data.

Hence we can see that Python Templates are used to substitute data into strings. With Templates, we gain a heavily customizable interface for string substitution (or string interpolation).
The Python Template class was added to the string module since Python 2.4. This class is intended to be used as an alternative to the built-in substitution options (mainly to %) for creating complex string-based templates and for handling them in a user-friendly way.

******End Of Article*******

More Articles of Vishal Lodhi:

Name Views Likes
Python string zfill 115 0
Python string swapcase 93 0
Python string title 97 0
Python string startswith 103 0
Python string replace 144 0
Python string translate 85 0
Python string rpartition 86 0
Python string partition 74 0
Python string splitlines 114 0
Python string rsplit 79 0
Python string split 76 0
Python string rindex 82 0
Python string rfind 106 0
Python string upper 80 0
Python string lower 82 0
Python string maketrans 90 0
Python string strip 81 0
Python string rstrip 92 0
Python string lstrip 80 0
Python string rjust 97 0
Python string ljust 96 0
Python string len 82 0
Python string join 76 0
Python string casefold 82 0
Python string isprintable 85 0
Python string encode 78 0
Python string isdecimal 85 0
Python string isidentifier 78 0
Python string isupper 78 0
Python string istitle 80 0
Python string isspace 100 0
Python string isnumeric 102 0
Python string isdigit 83 0
Python string islower 85 0
Python string isalpha 96 0
Python string isalnum 102 0
Python string index 88 0
Python string find 94 0
Python string expandtabs() 81 0
Python string endswith 92 0
Python string count 86 0
Python string capitalize 78 0
Python string center 85 0
Python string Introduction 99 0
Python string Template 141 0
Python string Formatter 145 0
Python string printable 199 0
Python string whitespace 146 0
Python string punctuation 104 0
Python string octdigits 87 0
Python string hexdigits 104 0
Python string digits 80 0
Python string ascii_letters 344 0
Python string ascii_lowercase 147 0
Python string ascii_uppercase 157 0
How to Create Download Manager in Python 524 0
Python random weibullvariate 165 0
python random paretovariate 135 0
Python random vonmisesvariate 178 0
Python random normalvariate 196 0
Python random lognormvariate 120 0
Python random gauss 120 0
Python random gammavariate 131 0
Python random expovariate 194 0
Python random betavariate 186 0
Python random triangular 117 0
Python random uniform 141 0
Python random random 117 0
Python random sample 183 0
Python random shuffle 179 0
Python random choices 234 0
Python random choice 166 0
Python random randint 149 0
Python random randrange 214 0
Python random getrandbits 141 0
Python random setstate 137 0
Python random getstate 178 0
Python random seed 168 1
Python random Introduction 175 0