Implement the concept of template in python

Implement the concept of template in python

In this article we see how can we implement the template concept in python.

  • In python String Template is a class in python. It is used to create templates of the string. Here the concept of format specifier is used. We can use string format() function to create a string , Basically , fields are replaced by their respective values.
  • Template class has two functions to create a string from the template.

  1. substitute(mapping , keywords): key based mapping is done here, substitutions from dictionary. If mapping and keyword arguments have same jet then TypeError will be thrown. If the key is not provided then keyError will be raised.

Example:

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)

#dictionay as sbustitute arguments

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.

2. safe_sustitute(mapping , keywords): It Behaves like same as substitute method, if key is not found so it doesn't raise KeyError and placeholder is returned in the result string.

Example:

from string import Template 

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

s= t.safe_substitute(name='Sundar pichai', job='CEO', company='Google')

print(s)        

Output:- Sundar pichai is the CEO of Google

Thank you for see this article.



To view or add a comment, sign in

Explore content categories