bhylu.com

Advertisements

Format Strings

An f-string combines literal text with expressions evaluated at that point in the program. It is useful for labels and reports where the value needs a particular display format.

Understand the idea

A colon inside the braces starts a format specification. Here .2f requests two digits after the decimal point. Formatting produces text; it does not improve the underlying numeric precision or turn an approximate float into exact decimal money. Keep calculations separate enough to inspect them when debugging.

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

item = "Notebook"
amount = 2.5
print(f"{item}: {amount:.2f}")

Read the result

The result is Notebook: 2.50. The stored amount is still a numeric value rather than the formatted string.

Try one change

Align three numeric values using a width in the format specification, then explain the difference between padding and rounding.