10. Formatting Strings#

Before this notebook, we used string concatenation and multiple arguments to print() to format strings. Now, we will use string interpolation to put values into strings in various formats.

Python offers three approaches to format strings:

To create an f-string:

  • place the letter f or F immediately before the start of a string literal

  • use variable names or expressions within curly braces to interpolate their values into the string.

1name = "Ada"
2score = 95
3
4print(f"{name} earned a score of {score}.")
5print(f"Next score target: {score + 5}")
Ada earned a score of 95.
Next score target: 100

By the end of this notebook, you will:

  • create f-strings to interpolate variables and expressions into formatted output

  • apply format specifications to control width, alignment, fill character, sign, and precision

  • format integers, floats, and strings for financial output (currency amounts, aligned columns, fixed-precision values)

  • use the = modifier for debugging f-string expressions

10.1. Formatting#

f-strings use the same formatting language as the new-style formatting; place a : after the variable name or expression to apply format codes.

{:[fill][alignment][sign][minwidth][.][maxchars]type}

  • An initial colon (‘:’).

  • An optional fill character (default ‘ ‘) to pad the value string if it’s shorter than minwidth.

  • An optional alignment character:

    • ‘<’ left (the default)

    • ‘>’ right

    • ‘^’ center

  • An optional sign for numbers. If + is specified, a plus symbol will be added to positive numbers. Negative numbers always have a minus sign.

  • An optional minwidth.

  • An optional period (‘.’) to separate minwidth and maxchars if both are defined. If only one is defined, assumed to be minwidth.

  • An optional maxchars. If this is a float type, then this specifies the precision.

  • the type:

Type

Description

s

string

d

integer

x

hexadecimal integer

o

octal integer

f

float

e

float in exponential format

g

decimal or exponential float

Full Format Specification

1year = 1838
2move_year = 1892
3school = "Duke University"
4city = "Trinity, North Carolina"
5print(f"In {year}, {school} was founded in {city}. {move_year-year} years later, {school} moved to Durham.")
In 1838, Duke University was founded in Trinity, North Carolina. 54 years later, Duke University moved to Durham.

As of Python 3.8, there’s also a useful shortcut to display variable names in the output. Just add = after their variable name or expression.

1year = 1838
2move_year = 1892
3school = "Duke University"
4city = "Trinity, North Carolina"
5print(f"In {year=}, {school=} was founded in {city}. {move_year-year=} years later, {school} moved to Durham.")
In year=1838, school='Duke University' was founded in Trinity, North Carolina. move_year-year=54 years later, Duke University moved to Durham.
1alphabet = "abcdefghijklmnopqrstuvwxyz"
2print("123456789012345678901234567890")
3print(f"{alphabet}")
4print(f"{alphabet:s}")
5print(f"{alphabet:X<30s}")
6print(f"{alphabet:X>30s}")
7print(f"{alphabet:X^30s}")
8print(f"{alphabet:30.5s}")
9print(f"{alphabet:>30.5s}")
123456789012345678901234567890
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyzXXXX
XXXXabcdefghijklmnopqrstuvwxyz
XXabcdefghijklmnopqrstuvwxyzXX
abcde                         
                         abcde
 1year = 1892
 2print("123456789012345678901234567890")
 3print(f"{year:d}")
 4print(f"{year:20d}")
 5print(f"{year:+20d}")
 6print(f"{year:0>20d}")  # can't specify minwidth and max chars as we could in the old-style
 7print(f"{year:0^8d}")
 8print(f"{year:^20d}")
 9print(f"{year:x}")
10print(f"{year:o}")
11print(f"{year:x^8d}")
123456789012345678901234567890
1892
                1892
               +1892
00000000000000001892
00189200
        1892        
764
3544
xx1892xx
1gain = 64.98712
2print("123456789012345678901234567890")
3print(f"{gain:f}")
4print(f"{gain:20f}")
5print(f"{gain:+20f}")
6print(f"{gain:020f}")
7print(f"{gain:20.8f}")
8print(f"{gain:20.2f}")
9print(f"{gain:<20.6f}")
123456789012345678901234567890
64.987120
           64.987120
          +64.987120
0000000000064.987120
         64.98712000
               64.99
64.987120           

10.2. Suggested LLM Prompts#

  • Explain the concept of f-strings in Python. Discuss when and why they are preferred over older formatting techniques like %-formatting and .format().

  • Describe the syntax for using f-strings, including how to embed variables, expressions, and format specifications. Provide examples.

  • Demonstrate how to format integers and floating-point numbers using f-strings. Explore options for specifying minimum field width, alignment, padding characters, precision, and alternative forms (e.g., scientific notation).

  • Compare and contrast f-strings, .format(), and %-style formatting. Provide examples showing when each method is most appropriate.

  • Discuss techniques for formatting strings using f-strings. Cover truncating long strings, padding with characters, aligning text in fields, and converting case. Provide examples for generating reports or displaying user input.

  • Provide examples of how f-strings are used in real-world applications, such as generating reports, formatting log messages, or building user interfaces. Discuss best practices for choosing the appropriate formatting method based on the requirements and readability concerns.

10.3. Review Questions#

  1. What is the syntax for using f-strings in Python? What version of Python introduced them?

  2. How do you apply format specifications (such as width, precision, alignment, and fill) within an f-string?

  3. What does the = modifier do in an f-string (Python 3.8+), and how would you use it?

answers

10.4. Drill#

For each of the steps below, use f-string syntax to produce the correct string for display.

  1. Define a variable year with a value of 2024.

  2. Display the string “2024 is the current year”.

  3. Display the string “xx2024xx”.

  4. Display the year value as hex.

  5. Display the string “0002024”.

  6. Define a variable pi with a value of 3.14159.

  7. Display the string “3.1416 is an approximate value of pi”.

  8. Display the string “xxx3.14xxx”.

  9. Display the string “0003.14159”.

  10. Display the string “ 3.14159000”.

answers

10.5. Exercises#

  1. Develop a business format letter with the following specifications:

    • It should be in a function produce_letter that takes any arguments needed to produce your letter.

    • The function should return a formatted string.

    • The string should be a multi-line string.

    • You should perform at least 5 formatting substitutions using f-strings.

  2. Write a function format_check_amount(value) that takes a float argument and returns a string in the format of $***XX.XX, where the leading asterisks are used to make the length of the output 10 characters and the precision is two digits.

  3. Write a function with the following declaration — def print_receipt(subtotal, tax_rate, tip_rate) — that prints the following:

     Subtotal: $     10.00
          Tax: $      0.50
          Tip: $      2.00
                ==========
        Total: $     12.50
    

    with the call: print_receipt(10.00, .05, .2)

Use f-strings for all of the numbers and equal signs.

Exercise Answers