Python f-strings: Format Numbers, Text and Tables
Gluing values into text with + quickly gets messy, because every number has to be converted with str() first. Formatted string literals, or f-strings, solve this. Put an f before the opening quote and write any expression inside curly braces; Python evaluates it and inserts the result.
Expressions inside braces
f"{name} bought {items} books" reads almost like the sentence it produces. The braces can hold any expression: arithmetic, method calls, indexing. Keep them short, though; if the expression is long, compute it on the line before and give it a name.
Format specifiers
After the expression you can add a colon and a format specifier that controls how the value is shown:
:.2fshows a float with exactly two decimals, rounding as needed.:,adds thousands separators; combine as:,.2f.:.1%multiplies by 100 and adds a percent sign.:<8,:>5and:^10pad to a width with left, right or center alignment. That is how you line up columns of a text table.:05dpads an integer with leading zeros to width 5.
Expected output
Ava bought 3 books for $41.50 Item | Qty Pens | 12 1,234,567.89 25.6% items * 2 = 6
The last line uses the = specifier, added in Python 3.8. It prints the expression text followed by its value, which is very handy when debugging. To show a literal brace, double it: f"{{" produces {.
Other formatting styles
You will meet two older styles in existing code. "{} and {}".format(a, b) uses the same specifiers as f-strings. The % operator, as in "%d items" % 3, is the oldest style and still works. For new code, f-strings are the clearest and also the fastest option.
Common mistakes
- Forgetting the
fprefix, so the braces are printed literally. - Using the same quote character inside the braces as around the string. Before Python 3.12 that was a syntax error; use the other quote type.
- Applying
:.2fto text. Format specifiers must match the value's type, or Python raisesValueError.
Summary
f"...{expr}..."inserts the value of any expression.:.2f,:,,:%control number display;<,>,^with a width align text.{expr=}prints the expression and its value for debugging.
Quiz: f-strings and formatting