Template String Substitution in Python


In this article, we show how to use and perform Template string substition in Python.

So when you use a Template string in Python, what you're basically doing is specifying a representation of data initially and then you are showing what data actually is.

An example of Template string substition is shown below.

So, the first thing we do is import the string module.

To perform Template string substition, the string module must be imported. Or else, the program will not work.

We then create a varaible called t. We set t equal to string.Template(). Inside of this function, we place the string, "This is the amount of money I have: $money"

Notice how the string contains the placeholder $money.

We then substitute the $money placeholder with the actual data.

We do this through the t.substitute() function. Inside of this function we write, money='$12.00'.

Once we run this t.substitute() function, this prints out, "This is the amount of money I have: $12.00".

You can do this with as many variables as you want.

Below is code that shows string substitution of multiple variables.

So, you now see how we have substituted multiple strings.

Template string substitution can also be performed using dictionaries, but this probably more complex.

You can see this in the example below.

So this is an alternate way of doing it.

Another thing to be aware of is that all placeholders must be defined, or else an error will be thrown.

The following code below will throw an error.

An error will be thrown in this code, because the placeholder, $price, is not defined.

However, there is a way around this.

By using the the safe_substitute() method instead of simply the substitute() method, any placeholders that aren't defined will not throw an error.

An example of this is shown below.

You may or may not want to use this, because it doesn't give good output. Usually, you would want an error to be thrown, so that you can put the correct values in place.

Template string substitution may not seem like it is very useful. However, you will see later that it actually is.

When using a web framework such as Django, Template is widely used. This is because when using a web framework, the representation of data is usually specified in one file, while the actual data is specified in another file. So the representation of data and the actual data are not together.

Thus, this is a very important topic to know.

Related Resources

How to Show All Tables of a MySQL Database in Python

How to Count the Number of Rows in a MySQL Table in Python

HTML Comment Box is loading comments...