Python Format Specifications
Learn Python format specifications through format(), including width, alignment, fill, numeric precision, and reusable formatting rules without re-teaching f-strings.
Intermediate
Python already has f-string coverage in the Strings lesson. This lesson goes one step deeper: it teaches the
format_spec part that controls how a value is presented, and the built-in
format() function that applies a format specification directly.
Start with format()
The built-in
format(value, format_spec) asks the value to produce its formatted representation using the supplied format specification. With an empty specification, the result normally matches
str(value).
Output
Ready to run.
Control width and alignment
A width reserves space for the formatted value. Alignment can be left, centered, or right. If you do not choose an alignment, the default depends on the value type; for text, left alignment is common, while numbers are normally right-aligned.
Output
Ready to run.
Choose a fill character
A fill character can make unused width visible. It is written together with an alignment option, so the first character supplies the fill and the second supplies the alignment.
Output
Ready to run.
Format numbers precisely
Numeric format specifications can control decimal precision and presentation. For example,
.2f asks for two digits after the decimal point, while
, requests grouping separators for supported numeric types.
Output
Ready to run.
Build a specification from values
A format specification can itself contain a value when it is used inside a formatted string. This is useful when the width or precision is part of the program state.
Output
Ready to run.
Conversion is different from formatting
In a formatted string,
!r,
!s, and
!a choose a conversion before the format specification is applied. The conversion answers “which representation should be formatted?”; the format specification answers “how should that representation or value be presented?”
Output
Ready to run.
Keep formatting separate from f-string syntax
The Strings lesson owns how f-strings insert expressions into text. This lesson owns the formatting specification itself and the
format() built-in. The same specification syntax can be used from f-strings,
str.format(), and
format(), so learning the specification once pays off in several contexts.
Quick check
Quick check
Which expression formats 12.5 with exactly two digits after the decimal point?
result =
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.