Skip to main content

Format spec mini-language

A format spec customises the string produced by format(x, spec). The same mini-language drives str.format, f-strings, and any type's __format__. This page is the complete grammar and per-type semantics.

Source-of-record: Python/formatter_unicode.c, format spec docs.

Grammar​

format_spec ::= [[fill]align][sign]["z"]["#"]["0"][width]
[grouping_option]["." precision][type]
fill ::= <any character>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= digit+
grouping_option ::= "_" | ","
precision ::= digit+
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G"
| "n" | "o" | "s" | "x" | "X" | "%"

Components​

Fill and align​

CharMeaning
<Left-align (default for non-numeric).
>Right-align (default for numeric).
^Centre.
=Pad between sign and digits. Numeric types only.

Fill is any character preceding the align character. Cannot be { or } directly (use repetition {{).

Sign​

CharEffect
+Sign on all numbers.
-Sign only on negatives (default).
Leading space on positives, - on negatives.

z flag​

Available since 3.11. For floats, coerces negative zero to positive zero before formatting.

# (alt form)​

Effect for b/o/x/X
Prefix with 0b, 0o, 0x, 0X respectively.
For e, f, g: always include a decimal point.
For g: do not strip trailing zeros.

Width and zero pad​

  • width is a minimum field width.
  • Prefix 0 enables zero-padding (numeric only) and implies = align.

Grouping​

CharEffect
,Use , as thousands separator.
_Use _ as thousands separator. Also groups every 4 hex digits for b, o, x, X.

Both options are exclusive.

Precision​

TypeMeaning of precision
Float f, e, EDigits after the decimal point.
Float g, GSignificant digits.
Float %Digits after the decimal point of the percentage.
sMaximum number of characters from the string.
OtherNot allowed.

Default precision for floats is 6.

Type​

Integer types​

CharOutput
bBinary.
cCharacter (Unicode code point).
dDecimal.
oOctal.
xHex lowercase.
XHex uppercase.
nLocale-aware decimal.

Float types​

CharOutput
eScientific, lowercase.
EScientific, uppercase.
fFixed-point.
FFixed-point, uppercase for inf/nan.
gGeneral; choose e or f based on magnitude.
GSame, uppercase variants.
nLocale-aware general format.
%Multiply by 100; append %.

String type​

CharOutput
sString form.

If no type is specified, the default is d for int, g for float, s for str.

Per-type __format__​

TypeDefault specNotes
intdEmpty spec equivalent to str(x).
floatemptyEmpty spec equivalent to str(x). Spec '' is not the same as 'g'.
complexemptyFormat real and imag parts; no separate spec per side.
strsWidth and precision honoured.
bytesnoneHas no __format__; falls back to object.__format__.
datetimestrftime fmtFormat spec is passed to strftime.
date / timestrftime fmtSame.
Decimalsimilar to floatSupports all numeric specs.
enum.EnumemptyDefault is str(member).

Conversion vs format​

f"{x!r:>10}" first applies the conversion (!r -> repr(x), !s -> str(x), !a -> ascii(x)), then formats the resulting string with the spec.

Width specified as a field​

In str.format and f-strings, width and precision can be parametrised:

f"{value:{width}.{precision}f}"
"{0:{1}}".format("x", 10)

The values inside braces must produce integers.

Default object.__format__​

If the type defines no __format__, object.__format__ is used. It accepts only an empty spec and returns str(self). Passing a non-empty spec to a type that does not understand it raises TypeError.

str.format extras​

"{0.attr}", "{0[key]}", "{name}", and combinations are allowed. The Formatter class (string.Formatter) exposes extension points: get_value, format_field, convert_field, vformat.

Gopy status​

FeatureState
Every spec componentComplete.
z zero-suppress flagComplete.
Width and precision via nested bracesComplete.
string.Formatter extension APIComplete.
Per-type __format__ (numeric, str)Complete.
Locale-aware n formattingComplete.

Reference​

  • CPython 3.14: format spec.
  • Python/formatter_unicode.c. Implementation.
  • format/. gopy's port.