String templates in Python

Templates are used to represent data in different forms. In particular, web templates are more attractive and readable for users. Templating usually involves a document (the template itself) and defined data.

Templates in Python

Templates are the final outputs of the program. However, they contain placeholders, instead of actual data, that can act as variables. The combination of templates and data produce a web page. One of the simplest forms is used to substitute values into a template in order to produce the final output (commonly known as String Templates).

Code

# A Python program to demonstrate working of string template
from string import Template
# We are creating a basic structure to print the name and
# marks of the students.
t = Template('Hi $name, you got $marks marks on the Math Exam')
#for i in Student:
print (t.substitute(name = 'Alex', marks = 56))

In the code, the Class template allows us to create simplified syntax by using placeholders identifiers formed by name and marks. The values for the placeholders are passed as a parameter in the substitute() function, which results in the final output.

One of the key applications for template is differentiating program logic from the details of multiple output formats. This makes it feasible to use custom templates for XML files, plain text reports, and HTML web reports.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved