How to use a different delimiter for Python Template?
Python template is a super powerful feature that can help you to fill the placeholders on the fly. But by default, the delimiter used by python for the template is a dollar $
, though this is perfect, at times you might need to use dollar in your final string and that is when it might be handy to overwrite the default delimiter with something uncommon. For example, we shall use %$%
in our case. Since Template is a class that uses delimiter property, so to override the delimiter we have to extend the class to which overrides the delimiter property.
from string import Template
class CustomTemplate(Template):
delimiter = '%$%'
template_string = "This is %$%custom string. This is %$%another string."
template = CustomTemplate(template_string)
output = template.substitute(custom="first", another="second")
print(output)
# Output
# This is first string. This si second string.
In the above example, we have extended CustomTemplate
which is overriding the delimiter
property with %$%
. In the following lines, you can see the use case of the substitute
to replace the content with the variables passed.