String Template Class in Python (original) (raw)

Last Updated : 15 Dec, 2022

In the String module, Template Class allows us to create simplified syntax for output specification. The format uses placeholder names formed by $ with valid Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with braces allows it to be followed by more alphanumeric letters with no intervening spaces. Writing creates a single escaped $.

Python String Template:

The Python string Template is created by passing the template string to its constructor. It supports $-based substitutions. This class has 2 key methods:

The substitute() method raises a KeyError when a placeholder is not supplied in a dictionary or a keyword argument. For mail-merge style applications, user-supplied data may be incomplete and the safe_substitute() method may be more appropriate — it will leave placeholders unchanged if data is missing:

Below are a few simple examples.
Example 1:

Python3

from string import Template

t = Template( 'x is $x' )

print (t.substitute({ 'x' : 1 }))

Output:

x is 1

Following is another example where we import names and marks of students from a list and print them using template.
Example 2:

Python3

from string import Template

Student = [( 'Ram' , 90 ), ( 'Ankit' , 78 ), ( 'Bob' , 92 )]

t = Template( 'Hi <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi><mo separator="true">,</mo><mi>y</mi><mi>o</mi><mi>u</mi><mi>h</mi><mi>a</mi><mi>v</mi><mi>e</mi><mi>g</mi><mi>o</mi><mi>t</mi></mrow><annotation encoding="application/x-tex">name, you have got </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">yo</span><span class="mord mathnormal">u</span><span class="mord mathnormal">ha</span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">e</span><span class="mord mathnormal" style="margin-right:0.03588em;">g</span><span class="mord mathnormal">o</span><span class="mord mathnormal">t</span></span></span></span>marks marks' )

for i in Student:

`` print (t.substitute(name = i[ 0 ], marks = i[ 1 ]))

Output:

Hi Ram, you have got 90 marks

Hi Ankit, you have got 78 marks

Hi Bob, you have got 92 marks

The below example shows the implementation of the safe_substitute method.
Example 3:

Python3

from string import Template

template = Template( '$name is the <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>j</mi><mi>o</mi><mi>b</mi><mi>o</mi><mi>f</mi></mrow><annotation encoding="application/x-tex">job of </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.05724em;">j</span><span class="mord mathnormal">o</span><span class="mord mathnormal">b</span><span class="mord mathnormal">o</span><span class="mord mathnormal" style="margin-right:0.10764em;">f</span></span></span></span>company' )

string = template.safe_substitute(name = 'Raju Kumar' ,

`` job = 'TCE' )

print (string)

Output:

Raju Kumar is the TCE of $company

Notice that we have not provided the “$company” placeholder any data, but it won’t throw an error, rather will return the placeholder as a string as discussed above.

Printing the template String

The “template” attribute of the Template object can be used to return the template string as shown below:
Example:

Python3

t = Template( 'I am <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi><mi>f</mi><mi>r</mi><mi>o</mi><mi>m</mi></mrow><annotation encoding="application/x-tex">name from </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span><span class="mord mathnormal" style="margin-right:0.10764em;">f</span><span class="mord mathnormal">ro</span><span class="mord mathnormal">m</span></span></span></span>city' )

print ( 'Template String =' , t.template)

Output:

Template String = I am namefromname from namefromcity

Escaping $ Sign

The $$ can be used to escape $ and treat as part of the string.
Example:

Python3

template = Template( '$$ is the symbol for $name' )

string = template.substitute(name = 'Dollar' )

print (string)

Output:

$ is the symbol for Dollar

The ${Identifier}

The Identifierworkssimilartothatof{Identifier} works similar to that of IdentifierworkssimilartothatofIdentifier. It comes in handy when valid identifier characters follow the placeholder but are not part of the placeholder.
Example:

Python3

template = Template( 'That <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi><mi>o</mi><mi>u</mi><mi>n</mi><mi>l</mi><mi>o</mi><mi>o</mi><mi>k</mi><mi>s</mi></mrow><annotation encoding="application/x-tex">noun looks </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal">n</span><span class="mord mathnormal">o</span><span class="mord mathnormal">u</span><span class="mord mathnormal">n</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">oo</span><span class="mord mathnormal" style="margin-right:0.03148em;">k</span><span class="mord mathnormal">s</span></span></span></span>{noun}y' )

string = template.substitute(noun = 'Fish' )

print (string)

Output:

That Fish looks Fishy

Another application for the template is separating program logic from the details of multiple output formats. This makes it possible to substitute custom templates for XML files, plain text reports, and HTML web reports.
Note that there are other ways also to print formatted output like %d for integer, %f for float, etc (Refer this for details)
Reference: https://docs.python.org/3.3/tutorial/stdlib2.html