Template from string to substitute words in a string

Python has a lot of useful modules that makes you save time if you know them. It is difficult to know all of them, so we will check for some of the interesting ‘hidden‘ features in the next post to be better aware of them.

Template

The class Template from the string module is the one we are going to talk today. With this class you can use a template string with placeholders that can be substituted with other words. I can think to a lot of cases that you could use this, so let’s get started.

Import Template

from string import Template

Create a string template

This string will have two placeholders with a $ sign before the word, attached to the word ($name and $city, in this case).

a = Template("""
This is something called $name
that lives in $city
""")

if we print this object ‘a’ with the method substitute and two keyword argument with the placeholders label:

print(a.substitute(name="John", city="Rome"))

you will have this output:

This is something called John
that lives in Rome

If you just pass one label to the method substitute, you will get an error, unless you use safe_substitute:

print(a.safe_substitute(name="John"))

>>> This is something called John
>>> that lives in $city

It will leave the $city placeholder as it is, without having an error message.

Using a dictionary

In the following example we use a dictionary to substitute the placeholders:

from string import Template
from random import choice

a = Template("""
This is something called $name
that lives in $city
""")

d = {
	"name" : choice(["john","Andrea","Martin"]),
}

print(a.safe_substitute(d))

The dictionary take an arbitrary name among a choice of 3. There is no value for $city and we used safe_substitute to avoid error messages.

The choice function comes fromt the random module that we imported in the second line

Utilities

 

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.