In Python, the string.Template class provides a safe and flexible way to substitute variables in a string template with values from a dictionary or other mapping object. The Template method uses a different syntax than the % operator or str.format() method, and is designed to make it easy to create templates that can be customized with different data.
Here's an example of using the string.Template class for string substitution:
from string import Templatename = 'John'age = 35template = Template('My name is $name and I am $age years old.')message = template.substitute(name=name, age=age)print(message) # Output: My name is John and I am 35 years old. |
In this example, we import the Template class from the string module and define a string template that contains two variables, $name and $age. We then create a dictionary that maps the variable names name and age to the values 'John' and 35, respectively, and use the substitute() method of the Template object to replace the variables in the template with the corresponding values. Finally, we print the resulting message to the console.
One advantage of the string.Template class is that it provides a safe way to substitute variables in a template, since it avoids many of the security issues that can arise with other methods of string substitution. For example, the % operator can be vulnerable to injection attacks if the values being substituted contain untrusted user input, whereas the string.Template class is designed to handle such cases safely. Additionally, the string.Template class provides a flexible syntax for defining variables in a template, making it easy to customize the template for different use cases.