Lesson 02-01: Printing with String Formatting

Learning Target: I can use string formatting to print strings with variables.

The Old Way

In order to print variables in a sentence, we know to use the + operator to combine strings.

>>> name = "Mark"
>>> print("His name is " + name)
His name is Mark

However, this gets complicated when a lot of variables get involved, especially numbers - like so:

>>> name = "Mark"
>>> lastname = "Twain"
>>> job = "Author"
>>> age = 74
>>> print("His name is " + name + " " + lastname + " and he was an " + job + " and he died at age " + str(age))
His name is Mark Twain and he was an Author and he died at age 74

The New Way

We can simplify this greatly by using string formatting. String formatting uses a special .format() function on a string that will allow us to implement placeholders. I think it’s best shown through example:

This time, we use the curly brace characters {} as a placeholder in our string. After the string, we immediately put .format() and then the name of the variable that will go into the {} placeholder. When you have multiple variables to insert, you put a {} for each one and then in the .format() function, list the variables in order. Here’s how it looks with the more complicated example:

This image shows which variable correlates with which placeholder

While it isn’t much shorter in terms of length, it is much easier to read! Not only that, but notice that we didn’t have to convert the variable age, which holds an integer, into a string to print it!

In general, you should always use string formatting when printing strings with variables. Other methods are messier and this is just best practice. For the rest of this course you will be expected to use string formatting in print statements.

Note that there are other ways to use string formatting, but we will not be covering them at this time.

Checks for Understanding

    ch0201-1: What is the main advantage to using string formatting when printing strings?
  • (A) It's easier to read and write
  • You can compare it against the older, harder-to-read way!
  • (B) It takes up less power
  • Nothing was mentioned here about power and efficiency.
  • (C) It's much much shorter
  • While it is shorter, it's not that much shorter. Try again!

In the following area, complete the code so that it runs according to the instructions #.

In the following area, complete the code so that it runs according to the instructions #.

Next Section - Lesson 02-02: Specific Letters with String Indexing