Skip to content

Python f-strings: the format spec, built visually

Everything after the colon in f"{value:,.2f}" is a tiny language. Pick the parts below and see the exact output Python produces.

build a format spec
f"{value:,.2f}"
output[1,234,567.89]
,grouping.2.precisionftype

▶ Check it in real Python

Format spec anatomy

{value:[[fill]align][sign][#][0][width][grouping][.precision][type]}
        ─────┬───── ──┬─ ┬  ┬ ──┬── ───┬──── ────┬────── ─┬──
   e.g.    *^         +  #  0   10     ,        .2        f

Every part is optional, but the order is fixed. That’s why :,.2f works and :.2f, raises a ValueError. The builder above follows the rules in the Python documentation’s “Format Specification Mini-Language”.

f-string cheat sheet

CodeOutputWhat it does
f"{name}"AdaInsert a variable
f"{a + b}"5Any expression
f"{x=}"x=42Self-documenting (3.8+)
f"{name!r}"'Ada'repr() instead of str()
f"{pi:.2f}"3.142 decimal places
f"{n:,}"1,234,567Thousands separator
f"{n:_}"1_234_567Underscore separator
f"{ratio:.1%}"45.7%Percentage
f"{n:05d}"00042Zero-pad to width 5
f"{s:<10}|"Ada |Left-align in 10
f"{s:>10}" AdaRight-align
f"{s:*^9}"***Ada***Center with fill
f"{n:+}"+42Always show sign
f"{255:#x}"0xffHex with prefix
f"{5:08b}"00000101Binary, 8 digits
f"{big:.2e}"1.23e+06Scientific notation
f"{dt:%Y-%m-%d}"2026-09-27Dates use strftime codes
f"{value:{width}.{prec}f}" 3.14Nested (dynamic) spec

Assumes name = "Ada", a, b = 2, 3, x = n = 42 (n = 1234567 for separators), pi = 3.14159, ratio = 0.4567, big = 1234567.

f-strings vs format() vs %

f"{x:.2f}", "{:.2f}".format(x) and format(x, ".2f") use the same spec language. The old "%.2f" % x style is similar but more limited. Use f-strings in new code; use str.format when the template is stored separately from the values (for example, loaded from a file).

More string tools: Python string methods and the Python cheat sheet.

Frequently asked questions

What is an f-string in Python?

A string literal prefixed with f, like f"Hello {name}". Expressions inside curly braces are evaluated at runtime and inserted into the string. F-strings were added in Python 3.6 (PEP 498).

How do I format a number to 2 decimal places?

Use the f presentation type with precision 2: f"{value:.2f}". Add a comma for thousands separators: f"{value:,.2f}".

How do I print literal curly braces in an f-string?

Double them: f"{{literal}} {value}" prints {literal} followed by the value.

What does the = specifier do?

f"{x=}" prints the expression and its value, e.g. x=42. It was added in Python 3.8 and is handy for quick debugging.

Can I use quotes inside the braces?

Since Python 3.12 (PEP 701) you can reuse the same quote type inside the braces, nest f-strings and write multi-line expressions. On older versions use the other quote type inside.