In 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 $:
Below is a simple example.
x is 1
Following is another example where we import names and marks of students from a list and print them using template.
Hi Ram, you have got 90 marks Hi Ankit, you have got 78 marks Hi Bob, you have got 92 marks
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:
Another application for 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)
This article is contributed by Siddharth Lalwani. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Template matching using OpenCV in Python
- Python | Document field detection using Template Matching
- self in Python class
- First Class functions in Python
- Class as decorator in python
- Python | Check if given string can be formed by concatenating string elements of list
- String slicing in Python to check if a string can become empty by recursive deletion
- Class & Instance Attributes in Python
- Changing Class Members in Python
- Class or Static Variables in Python
- Python | Check if string ends with any string in given list
- Python | Using variable outside and inside the class and method
- Python | Avoiding class data shared among the instances
- CBSE Class 11 | Computer Science - Python Syllabus
- CBSE Class 12 | Computer Science - Python Syllabus