Coding

Python f-string Guide: Formatting, Decimals, Padding, Debugging

An f-string is a string literal prefixed with f in which any Python expression inside curly braces is evaluated and inserted: f"Hello {name}". Add a format spec after a colon to control the output, for example f"{price:,.2f}" for two decimals with thousands separators, or f"{x=}" to print the variable name and its value while debugging.

Basic f-string syntax

name = "Alex"; items = 3; price = 1234.5
print(f"{name} bought {items} items")
print(f"Total: {price * items:,.2f}")

Output (Python 3.12):

Alex bought 3 items
Total: 3,703.50

Any expression works inside the braces: arithmetic, method calls, indexing, function calls. PEP 498, which introduced f-strings in Python 3.6, describes them as "an expression evaluated at run time", using the variables in scope where the f-string appears. The prefix can be f or F, and combines with r for raw strings (rf"C:\{folder}").

A replacement field has up to four parts, in this order:

{expression = !conversion :format_spec}
   value     |      |          |
             |      |          how to format it (after the colon)
             |      !r, !s or !a
             show "expression=" too (debug)

How to format decimals and numbers

The part after the colon uses Python's Format Specification Mini-Language, the same one format() uses. The most useful specs:

Goalf-stringOutput
2 decimal placesf"{3.14159:.2f}"3.14
Thousands separatorf"{1234567.891:,.2f}"1,234,567.89
Underscore separatorf"{1234567:_}"1_234_567
Percentagef"{0.256:.1%}"25.6%
Zero-padded widthf"{42:08.3f}"0042.000
Hexadecimalf"{255:x}", f"{255:#x}"ff, 0xff
Binaryf"{255:b}"11111111
Scientific notationf"{1e6:.2e}"1.00e+06
General (trims zeros)f"{1234.5678:g}"1234.57
Always show signf"{5:+}"+5

Every output in the table was produced by running the expression in Python 3.12. Two details catch people out. .2f means two digits after the decimal point, while .2g means two significant digits. And % multiplies by 100 for you, so pass the fraction (0.256), not the percentage (25.6).

The z option (Python 3.11+) turns a negative zero after rounding into a plain zero: f"{-0.0001:.2f}" gives -0.00, while f"{-0.0001:z.2f}" gives 0.00.

How to pad and align text

Give a width, optionally preceded by an alignment character: < left, > right, ^ centre. A character before the alignment sets the fill:

name = "Alex"
print(f"|{name:<10}|{name:>10}|{name:^10}|")
print(f"|{name:*^10}|")
|Alex      |      Alex|   Alex   |
|***Alex***|

Strings align left by default and numbers align right. That makes simple text tables easy:

rows = [("apples", 3, 0.5), ("melons", 12, 2.25)]
for item, qty, unit in rows:
    print(f"{item:<8}{qty:>4}{unit:>8.2f}")
apples     3    0.50
melons    12    2.25

Width and precision from variables

The format spec can itself contain replacement fields, one level deep:

width = 12; prec = 3
print(f"|{3.14159265:{width}.{prec}f}|")
|       3.142|

How to format dates in an f-string

Objects can define their own format specs. For datetime, the spec is a strftime pattern:

from datetime import datetime, timezone
d = datetime(2026, 11, 3, 14, 5, tzinfo=timezone.utc)
print(f"{d:%Y-%m-%d %H:%M}")
2026-11-03 14:05

Debugging with {x=}

Since Python 3.8, an equals sign after the expression prints the expression text, then its value:

items = 3; price = 1234.5
print(f"{items=}")
print(f"{price * items = :.1f}")
items=3
price * items = 3703.5

Spaces around the = are kept in the output, and you can still add a format spec after it. It is the quickest way to inspect values without typing each name twice.

!r, !s and !a conversions

!r calls repr() on the value before formatting, !s calls str() and !a calls ascii(). !r is handy for spotting stray whitespace or seeing the type of a value:

name = "Alex"
print(f"{name!r}")
'Alex'

What changed in Python 3.12

PEP 701 rewrote how f-strings are parsed, and the language reference notes that "nested strings, comments, and backslashes are now permitted" inside the braces. On 3.12 and later both of these work; on 3.11 and earlier they are syntax errors:

user = {"name": "alex"}
print(f"Hello {user["name"]}")      # same quote type inside the braces

lines = ["a", "b"]
print(f"{"\n".join(lines)}")        # backslash inside the braces
Hello alex
a
b

If your code must also run on older Pythons, use the other quote type inside the braces (f"{user['name']}") and move backslash expressions into a variable first.

Literal braces and other rules

  • Literal braces: double them. f"{{literal braces}} {name}" prints {literal braces} Alex.
  • Not docstrings: an f-string at the top of a function is not a docstring, even without any braces in it.
  • Multi-line: triple-quoted f-strings work, and from 3.12 an expression inside the braces can span lines and include comments.

f-strings vs str.format() vs %

All three produce the same result for everyday formatting, and they share the same format specs: f"{x:.2f}", "{:.2f}".format(x) and "%.2f" % x all give the same text. The difference is where the values go. An f-string puts each expression right where it appears, so there is no counting of positions and no list of arguments to keep in sync. str.format() keeps the template separate from the values, which is what you want when the template comes from somewhere else. The % operator is the oldest style; you still meet it in older code and in the logging module.

When not to use an f-string

  • SQL queries. Building SQL with an f-string invites SQL injection. The sqlite3 documentation says to "always use placeholders instead of string formatting": cur.execute("SELECT * FROM users WHERE name = ?", (name,)). Other database drivers have the same parameter mechanism.
  • Logging calls. The logging HOWTO passes variable data as separate arguments, logging.warning('%s before you %s', 'Look', 'leap!'), and notes that formatting is "deferred until it cannot be avoided". With an f-string, the message is formatted even when the log level means it is thrown away.
  • Templates supplied as data. An f-string is code: it is evaluated where it is written. For a format string loaded from a file or a translation catalogue, use str.format() or string.Template, which PEP 498 left in place.

Frequently asked questions

Which Python version introduced f-strings?
Python 3.6, through PEP 498. The {x=} debug form was added in Python 3.8, and Python 3.12 (PEP 701) removed most restrictions on what can go inside the braces, such as reusing the same quote character and using backslashes.
How do I print a literal curly brace in an f-string?
Double it. f'{{' produces { and f'}}' produces }. For example, f'{{x}} = {x}' with x = 5 prints {x} = 5.
Can I use an f-string as a docstring?
No. The Python language reference states that formatted string literals cannot be used as docstrings, even if they contain no expressions; the function's __doc__ will be None. Use a plain string literal for docstrings.
Are f-strings faster than format() or %?
In a quick timeit run on Python 3.12, formatting a short string took about 102 ns with an f-string, 172 ns with % and 196 ns with str.format(). That is faster, but a difference of tens of nanoseconds per call rarely matters, so choose on readability. The case where it matters is logging: passing arguments separately lets the logging module defer formatting until a message is actually emitted, which an f-string cannot do.

Sources