Technical skill practice

Python Format String: Align a Small Report without Changing Values

A Python format string controls how values are displayed. In an f-string, an expression goes inside braces and an optional format specification follows a colon. Width and precision can make a report readable, but formatting a number does not change the value stored in its variable.

Start with a small, explicit task

Display two fictional measurements in aligned columns with two decimal places. Include a literal pair of braces in the heading. Check the actual spaces with repr so alignment is visible even when a proportional font would hide the difference.

Run the complete example

This original example was checked with Python 3.12.14. Save it as python_format_string.py and run it with Python 3.12. It uses only the standard library. The assertions check the stated results.

Expected output

{reading report}

'left 2.38'

'right 12.50'

readings = [("left", 2.375), ("right", 12.5)]
heading = f"{{reading report}}"
lines = [f"{name:<6} {value:>6.2f}" for name, value in readings]
assert heading == "{reading report}"
assert lines == ["left     2.38", "right   12.50"]
assert readings[0][1] == 2.375
print(heading)
for line in lines:
    print(repr(line))

Explain the result

The name field is left-aligned within six character positions. The numeric field is right-aligned within six positions and shown with two digits after the decimal point. The extra space between fields is separate from each field’s padding. repr exposes the exact resulting spaces so you can compare them with the assertions.

The displayed 2.38 is a representation of the original 2.375, which remains unchanged in readings. This example uses an exactly representable binary fraction, avoiding an unrelated approximation puzzle. Doubling the opening and closing braces creates the literal heading braces instead of asking the f-string to evaluate a name.

Avoid these mistakes

A field width is a minimum, not a limit: a long name or a large number can extend beyond it. Do not use display formatting as a substitute for a numeric rounding or storage policy. If exact decimal rules matter, choose a suitable representation and test those rules separately.

Questions, answered

Does .2f change my variable?

No. The output string has two decimal places, while the original checked value is still 2.375.

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

Double them, as the heading example does with {{ and }}.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.