Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

"Old-School" String Formatting in Python

Give Feedback

In this lesson, you’ll get a review of the two old school string formatting methods:

  1. % string formatting
  2. str.format() method

Here is an example of % string formatting:

>>>
>>> name = "Eric"
>>> age = 74
>>> "Hello, %s. You are %s." % (name, age)
'Hello Eric. You are 74.'
You’ll see how using this approach can lead to problems when writing longer strings.

The lesson also covers the str.format method, which is an improvement on % formatting. Here’s the code for the examples used:

>>>
>>> "Hello, {}. You are {}.".format(name, age)
'Hello, Eric. You are 74.'

And:

>>>
>>> person = {'name': 'Eric', 'age': 74}
>>> "Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])
'Hello, Eric. You are 74.'

00:00 Prior to Python 3.6, you had two options for formatting your strings. You could do %-formatting or you could do str.format(). As a review, let me show you both of them.

00:11 %-formatting is the OG, original style in the original Python docs. Here’s what it looks like in practice. We’ll set up a variable and we’ll give it a name.

00:22 To use that variable in a string, you’d use %s within your string, and then at the end of it, put percent (%) and then the name of the variable.

00:32 Then it will plug in the variable name directly into that placeholder. Let’s say we had more than one variable. We still have namewhich we entered in earlier, I know—then age.

00:48 Let’s put that as a integer. Now we have two variables that we’d like to add to our string. We’ll do the same with the name, but then we’ll put in "You are" this age, and that will be our other variable. So in this case, we have now two variables we’re going to plug in. To do that, we would add % and then enter it in as a tuple, (name, age), and it plugs it in.

01:15 So, it seems simple enough, right? What if you had a lot more variables? This time we’ll have a first and a last name, along with our age, and now we’ll have a profession and an affiliation. To put all these in a single string, it starts to get a little messy. You know, we’d have to sit here and count the number of %s as it goes along to make sure you have them in the right order, in which one you’re replacing.

01:47 And then at the end here, we’ll need to enter in all our variables as a very long tuple, and make sure we get them in the right order, ha. All right, that looks right.

02:01 Great! But this could be very confusing, especially if someone has to read your code later. They’re going to have to do a lot of counting. Fortunately, there are better ways to do this. Let’s talk about option two, str.format().

02:16 These were introduced in Python 2.6. In this case, we can put placeholders in our string using curly brackets, {}. And at the very end of our string we would say .format().

02:30 And then we can put arguments in. In this case, name and age. We had entered name and age earlier, so when I hit Return here, it will fill them in. Great!

02:43 We can also reference the variables by their index. Let’s say we did this a little differently. And we said, this is index 1,

02:57 and this one’s index 0.

03:01 So the same, .format(), but we’d have them in reverse order, age, name. So we get the same result. In this case, if we needed to reference them by index we could across multiple variables. One other added advantage is as you insert variable names, you get the added perk of being able to pass objects and then reference parameters and methods in between the braces. Let’s try it out. In this case, we could make a dictionary.

03:30 And for our string this time, we can reference the name,

03:37 and again .format().

03:42 And then we can pull them out of the dictionary.

03:48 Let’s try it out. I just need to close my statement. There we go. We can also use double asterisks (**) to unpack our arguments. If we use that same dictionary we had a minute ago, again referencing here, we could try it with "Hello" and the "{name}". And this time when we do .format(), we’re going to have it unpack the arguments.

04:11 It looks like str.format() has some big advantages over %-formatting. But what are some problems that you might run into with it? We’re still going to get really verbose when we have lots of parameters and longer strings, so let’s take a look at what that might look like. All right.

04:25 Let me have you check to see that all these variables are still here. That looks good. So, what would it look like to do a big, long print statement with that?

04:37 Extend the string here.

04:46 All right, close the first print(). And now .format(), and first_name will equal first_name and last_name, last_name, age will equal age. Extend again, here.

05:03 profession will equal profession, and affiliation will equal affiliation. All right. Looks like I’ve closed my parentheses. There we go!

05:16 If we had all these variables in a dictionary, we could have unpacked them using the technique we did a moment ago, but I hope you can agree that there has to be a better way to do this.

05:25 So that’s what I’m going to show you next.

Terry Spotts on March 14, 2019

What about .format_map(dictionary)? I think it has some performance advantages over .format(**dictionary)?

Dan Bader RP Team on March 14, 2019

@Terry: Thanks, that’s interesting! If I remember correctly from my research for this article using f-strings was faster than either one of those, so that’s probably what I’d go with. But I can see how .format_map would beat .format performance-wise.

Chaitanya on March 23, 2019

Hi,

Can we run the expressions with in the strings using format method.

Eg:

person = {"name": "John", "age": 30}
"Hello {per}.name!!! Wow your age is {per}.age".format(per=person)

which is failing, but I want access the john and 30 within the string by using dot notation within string.

Dan Bader RP Team on March 23, 2019

@Chaitanya: You can’t use dot notation on a dict but the following will work:

>>> person = {"name": "John", "age": 30}
>>> "Hello {name}!!! Wow your age is {age}".format(**person)
'Hello John!!! Wow your age is 30'

Become a Member to join the conversation.