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.
| 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' |