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.'


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

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


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


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.