"Old-School" String Formatting in Python

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

Comments & Discussion

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.