Skip to ContentGo to accessibility pageKeyboard shortcuts menu
OpenStax Logo

Learning objectives

By the end of this section you should be able to

  • Use f-strings to simplify output with multiple values.
  • Format numbers with leading zeros and fixed precision.

F-strings

A formatted string literal (or f-string) is a string literal that is prefixed with "f" or "F". A replacement field is an expression in curly braces ({}) inside an f-string. Ex: The string f"Good morning, {first} {last}!" has two replacement fields: one for a first name, and one for a last name. F-strings provide a convenient way to combine multiple values into one string.

Checkpoint

Printing an f-string

Concepts in Practice

Basic f-strings

1.
What is the output of the following code?
animal = "dog"
says = "bark"
print(f"My {animal} says {says} {says} {says}")
  1. My dog bark bark bark bark
  2. My dog says bark bark bark
  3. Error
2.
What is the output of the following code?
temp = "hot"
food = "potato"
print("{temp} {food}")
  1. {temp} {food}
  2. hot potato
  3. Error
3.
How can the following code be rewritten using an f-string?
print(x, "+", y, "=", x + y)
  1. print(f"x + y = {x+y}")
  2. print(f"{x + y} = {x + y}")
  3. print(f"{x} + {y} = {x+y}")

Formatting numbers

Programs often need to display numbers in a specific format. Ex: When displaying the time, minutes are formatted as two-digit integers. If the hour is 9 and the minute is 5, then the time is "9:05" (not "9:5").

In an f-string, a replacement field may include a format specifier introduced by a colon. A format specifier defines how a value should be formatted for display. Ex: In the string f"{hour}:{minute:02d}", the format specifier for minute is 02d.

Format Description Example Result

d

Decimal integer (default integer format).

f"{12345678:d}"

'12345678'

,d

Decimal integer, with comma separators.

f"{12345678:,d}"

'12,345,678'

10d

Decimal integer, at least 10 characters wide.

f"{12345678:10d}"

'  12345678'

010d

Decimal integer, at least 10 characters wide, with leading zeros.

f"{12345678:010d}"

'0012345678'

f

Fixed-point (default is 6 decimal places).

f"{math.pi:f}"

'3.141593'

.4f

Fixed-point, rounded to 4 decimal places.

f"{math.pi:.4f}"

'3.1416'

8.4f

Fixed-point, rounded to 4 decimal places, at least 8 characters wide.

f"{math.pi:8.4f}"

'  3.1416'

08.4f

Fixed-point, rounded to 4 decimal places, at least 8 characters wide, with leading zeros.

f"{math.pi:08.4f}"

'003.1416'

Table 3.3 Example format specifiers. The table shows common ways that numbers can be formatted. Many more formatting options are available and described in Python's Format Specification Mini-Language.

Concepts in Practice

Formatting numbers

4.
What f-string formats a date as MM/DD/YYYY?
  1. f"{month:02d}/{day:02d}/{year}"
  2. f"{month:2d}/{day:2d}/{year}"
  3. f"{month}/{day}/{year}"
5.
What statement displays the variable money rounded to two decimal places?
  1. print(f"{money:2d}")
  2. print(f"{money:2f}")
  3. print(f"{money:.2f}")
6.
What format specifier displays a floating-point number with comma separators and rounded to two decimal places?
  1. .2,f
  2. ,.2f
  3. ,d.2f

Try It

Mad lib (f-string)

A mad lib is a funny story that uses words provided by a user. The following mad lib is based on four words (user input in bold):

    Enter a name: Buster
    Enter a noun: dog
    Enter an adjective: super
    Verb ending in -ing: swimming
    
    Buster, the super dog, likes to go swimming.

Most of the code for this mad lib is already written. Complete the code below by writing the f-string.

Try It

Wage calculator

You just landed a part-time job and would like to calculate how much money you will earn. Write a program that inputs the time you start working, the time you stop working, and your hourly pay rate (example input in bold):

    Starting hour: 9
    Starting minute: 30
    Stopping hour: 11
    Stopping minute: 0
    Hourly rate: 15

Based on the user input, your program should calculate and display the following results:

    Worked 9:30 to 11:00
    Total hours: 1.5
    Payment: $22.50

For this exercise, you need to write code that (1) calculates the total payment and (2) formats the three output lines. Use f-strings and format specifiers to display two-digit minutes, one decimal place for hours, and two decimal places for payment. The input code has been provided as a starting point.

Assume the use of a 24-hour clock. Ex: 16:15 is used instead of 4:15pm.

Citation/Attribution

This book may not be used in the training of large language models or otherwise be ingested into large language models or generative AI offerings without OpenStax's permission.

Want to cite, share, or modify this book? This book uses the Creative Commons Attribution License and you must attribute OpenStax.

Attribution information
  • If you are redistributing all or part of this book in a print format, then you must include on every physical page the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
  • If you are redistributing all or part of this book in a digital format, then you must include on every digital page view the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
Citation information

© Jul 30, 2024 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution License . The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.

This book utilizes the OpenStax Python Code Runner. The code runner is developed by Wiley and is All Rights Reserved.