How to Concatenate Python Template Strings?

Estimated read time 2 min read

To concatenate Python template strings, you can use the Template class from the string module. The Template class provides a way to create string templates with placeholders that can be replaced with values. Here’s an example:

from string import Template

# Create template strings
template1 = Template("Hello, $name!")
template2 = Template("The result is: $result")

# Substitute values into templates
str1 = template1.substitute(name="Alice")
str2 = template2.substitute(result=42)

# Concatenate template strings
concatenated_str = str1 + " " + str2

# Print the result
print(concatenated_str)  # Output: Hello, Alice! The result is: 42

In this example, we first create two template strings using the Template class. The placeholders in the templates are denoted by the $ sign followed by the placeholder name.

We then use the substitute() method on each template to replace the placeholders with specific values. The substitute() method takes keyword arguments where the argument name corresponds to the placeholder name and the argument value is the value to substitute.

After substituting the values into the templates, we can concatenate the resulting strings using the + operator. In this case, we concatenate the two template strings with a space in between.

Finally, we print the concatenated string, which contains the substituted values from the templates.

Using the Template class provides a flexible way to concatenate template strings while allowing for placeholder substitution.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply