Introduction to Python ProgrammingXYZ Homework Edition

⇩ Download ▾

3.2 Formatted strings

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.

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.

Table 3.3 Example format specifiers.
FormatDescriptionExampleResult
dDecimal integer (default integer format).f"{12345678:d}"'12345678'
,dDecimal integer, with comma separators.f"{12345678:,d}"'12,345,678'
10dDecimal integer, at least 10 characters wide.f"{12345678:10d}"'  12345678'
010dDecimal integer, at least 10 characters wide, with leading zeros.f"{12345678:010d}"'0012345678'
fFixed-point (default is 6 decimal places).f"{math.pi:f}"'3.141593'
.4fFixed-point, rounded to 4 decimal places.f"{math.pi:.4f}"'3.1416'
8.4fFixed-point, rounded to 4 decimal places, at least 8 characters wide.f"{math.pi:8.4f}"'  3.1416'
08.4fFixed-point, rounded to 4 decimal places, at least 8 characters wide, with leading zeros.f"{math.pi:08.4f}"'003.1416'

Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or ADA Title II. Every page is built against an automated accessibility gate, and the published editions will meet ADA Title II requirements when they release in late September 2026. If something is unusable, please tell us.