Skip to main content

Section 7.10 Formatting Strings

Perhaps you have gotten tired of writing output like this:
years = int(input("Enter your age in years:"))
days = years * 365
print(days, "days is about", years, " years.")  # or
print(str(days) + " days is about " + str(years) + " years.")
Not only is it tedious to put in all the commas or plus signs, it doesn’t give you very good control over the output. For example, when you do monetary calculations, the output isn’t given with exactly two digits after the decimal point.
Python provides two ways to control output better and make the code easier to write. One of these is the format method, which has been available since Python version 3. The newer, even better way to format your output is through the magic of f-strings (short for “formatted literal strings”). These were introduced to Python at the end of 2016, and they are the topic of the rest of this page.

Subsection 7.10.1 f-strings

Consider this Python program that produces the cube of an input number:
x = float(input("Enter a number: "))
x_cubed = x * x * x
print("When x is", x, "x cubed is", x_cubed)
An f-string lets us put the variables inside the string instead of needing to put multiple items in the parentheses. In the following program, we have put the letter f before the opening quotes and put the variable names inside braces { and }.
One extra advantage of f-strings is that we now have complete control over the spacing; we can put a comma immediately following the value of x and the period directly after x_cubed. While you could achieve the same effect without f-strings, it would be more difficult.
But wait—there’s more! You can put Python expressions in the braces.
Use this feature sparingly. Do not put long, complex expressions into an f-string. Instead, create variables to hold the values of the expression and print the variables in the f-string.

Subsection 7.10.2 Controlling Decimal Digits

We now have the question of how to control decimal points. Let’s return to our discount example:
subtotal = 34.95
total = 34.95 * 0.93 # 7% discount
print(f"Your discounted price is ${total}.")
Here’s the output:
Your discounted price is $32.5035.
Ugly, isn’t it? In order to control the number of digits after the decimal point, we need to add something to the braces:
Here’s what the :.2f means:
  • The colon : introduces the extra formatting information.
  • The .2 says “we want two digits after the decimal point.”
  • The f says “the variable is a number that can have decimal places.”
If you wanted four digits after the decimal point, you would use :.4f; if you wanted only one digit, you’d use :.1f.

Subsection 7.10.3 Advanced Topic: Aligning Output

Consider this program. When you run it, the numbers don’t quite line up:
You can fix that by specifying the width that you want the number to take up. In the preceding program, change the .3f to 8.3f on lines 3 and 4. This says “use at least 8 spaces to display this number, with 3 digits to the right of the decimal point.” That means there will be four digits to the left of the decimal point, since 4 + 3 + 1 (for the decimal point) adds up to eight. When you run the program again, you’ll see everything line up nicely.

Subsection 7.10.4 Advanced Topic: Additional Formatting Codes

If you need to format an integer (usually to control its alignment), you use d instead of f. Since integers don’t have decimal digits, the format specifier doesn’t have a . in it.
If you want leading zeros on a number (for example, when displaying the minutes in a time), use a 0 before the width, as in the following example:
Note that the leading zeros don’t appear unless they are required to fill out the minimum width.
If you have a decimal value (such as 0.0737) that you want to display as a percentage, use the % specifier. Here is an example of both of these:
discount = 0.0737
print(f"Discount {discount:.1%}") # output: Discount 7.4%
For a complete description of all the formatting codes, see the Python documentation 1 .

Subsection 7.10.5 Exercises

Checkpoint 7.10.1.

    What is printed by the following statements?
    x = 2
    y = 6
    print(f'sum of {x} and {y} is {x + y}; product is {x * y}.')
    
  • Nothing - it causes an error
  • It is legal format syntax: put the data in place of the braces.
  • sum of {2} and {6} is {8}; product is {12}.
  • The braces don’t appear in the output.
  • sum of 2 and 6 is 8; product is 12.
  • Yes, correct substitutions!

Checkpoint 7.10.2.

    What is printed by the following statements?
    v = 2.34567
    print(f'{v:.1f}, {v:.2f}, {v:.7f}')
    
  • 2.34567, 2.34567, 2.34567
  • The numbers before the f in the braces give the number of digits to display after the decimal point.
  • 2.3, 2.34, 2.34567
  • Close, but round to the number of digits and display the full number of digits specified.
  • 2.3, 2.35, 2.3456700
  • Yes, correct number of digits with rounding!
docs.python.org/3/library/string.html#formatspec