bhylu.com

Advertisements

String Formatting

Formatting describes how a value should look to a reader. It is separate from how the value is stored or calculated.

Understand the idea

Format specifications can control decimal places, alignment, width, and separators. An f-string evaluates expressions now, while a format template can be filled later. Use Decimal or an integer-minor-unit model when exact monetary rules matter; adding two display digits does not remove floating-point approximation.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

amount = 1250.5
print(f"Total: {amount:,.2f}")
print(f"{'Python':<10} {3:>3}")

Read the result

The first result is Total: 1,250.50. The second aligns a label and a count using explicit widths.

Try one change

Format a negative amount and a large amount, then check whether the resulting labels remain understandable.