String class template in Python



Below is a simple example.

 

# Simple Python templaye example

from string import Template

 
# Create a template that has a placeholder for the x value

t = Template ( `x is $ x` )

 
# Substitute the x value in the template above

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

Output:

 x is 1 

Below is another example in which we import the names and grades of the students from the list and print them using the template.

# Python program that demonstrates how the inline template works

from string import Template

  
# Student list stores the names and grades of three students

Student = [( `Ram` , 90 ) , ( `Ankit` , 78 < / code> ), ( `Bob` , 92 )]

 
# We create a basic structure for printing the name and
# student grades.

t = Template ( ` Hi $ name, you have got $ marks marks` )

 

for i in Student:

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

Output:

 Hi Ram, you`re 90 ratings Hi Ankit, you have 78 ratings Hello Bob, you have 92 ratings 

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

Another template application separates the program logic from the details of multiple output formats. This allows you to replace custom templates for XML files, text reports, and HTML web reports.

It should be noted that there are other ways to print formatted output as well, like% D for an integer,% F for a float, and etc. (see this for details)

Link: https://docs.python.org/3.3/tutorial/stdlib2.html

This article is contributed by Siddharth Lalwani. If you like Python.Engineering and would like to contribute, you can also write an article and mail it to [email protected] See your article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you`d like to share more information on the topic under discussion