String Formatting With Template Strings
Learn how to use the fourth string formatting method, Template Strings. You’ll see that template strings are simple and ideal when dealing with data generated by the user:
>>> from string import Template
>>> t = Template('Hey, $name!')
>>> t.substitute(name=name)
'Hey, Bob!'
00:00 Moving on to the fourth major method of string formatting: template strings. Now, template strings are simpler feature-wise and they’re available in the standard library.
00:12 The syntax is simplified and the most common time to use them is when users are supplying the strings for your program. Now, that’s important to remember because the thing is, it is possible for formatted strings to access arbitrary variables inside your program.
00:31 This is technically a vulnerability because a malicious actor could input specifically-formatted strings hoping to exfiltrate something, like a data or a password, from your program.
00:44 That’s why it is suggested to use template strings when users are supplying input for your program. They are safer. With that being said, let’s move back into the scenario.
00:56
Just to review, our two variables that we have for the scenario are errno
, which contains an integer, and name
, 'Bob'
. So, to use template strings, the first thing we’re going to do is import a class, or an object, called Template
.
01:15
And then we’re going to instantiate an instance of this Template
object. We’ll name it t
and we’ll give it a string. When you’re using template strings, a dollar sign ($
) indicates somewhere a substitution is going to take place.
01:33 And then a keyword that we’re going to substitute.
01:38
So, there’s our t
object. Now, when you have a Template
object, there’s a built-in method called .substitute()
. If I can spell that, .substitute()
. And you call that method and pass it the variable that you want to substitute.
01:56
So, going back to our example, we need a string that provides both the name
'Bob'
, and our hex value. With template strings, we don’t have an output format specifier per se, so we’ll have to manually transform the errno
value into hex.
02:16 Follow along with me here. That’ll look like this.
02:21
Again, we’re going to set up a t
object and build our string inside of it.
02:35
Now that we have our t
object available, we’re going to call .substitute()
,
02:41
and we’re going to substitute name
where we see $name
,
02:47
and we’re going to substitute wherever we see $error
, we’re going to substitute errno
. We want it transformed into hex first. Nice!
02:59 That concludes the four major ways of formatting strings. I’ll see you in the review!
Become a Member to join the conversation.