Format spec mini-language
Interactive lab
Try it: Format spec mini-language
How Python reads a format spec like *^+14,.2f in f-strings, str.format() and format(): fill, align, sign, #, 0, width, grouping, precision and type — and how it then builds the output, rounding floats exactly the way Python does.
How it works
- Parse the spec left to right: [[fill]align][sign][z][#][0][width][,|_][.precision][type].
- Check the pieces against the value's type (int, float, str); invalid combinations raise the same ValueError Python raises.
- Turn the value into digits: ints in base 10/16/2/8; floats rounded half-to-even on their exact binary value (so 2.675 → 2.67).
- Add the sign, 0x/0b/0o prefix, thousands separators and the decimal point or exponent.
- Pad with the fill character to the width: left, right, centred, or between the sign and the digits (=).
Default run (18 steps): format(-1234.5678, '*^+14,.2f') — same as f"{-1234.5678:*^+14,.2f}". Read the spec from left to right. … format(-1234.5678, '*^+14,.2f') → '**-1,234.57***' (14 characters).
Simplified: int, float and str values only (no custom __format__, no locale-dependent 'n' grouping); width up to 60 and precision up to 50.
Educational simulation
Loading the simulation…