Ad space (banner)
🐍Python Lessons
Lesson 50 / 69

Formatting Numbers (padding digits, decimal places)

This lesson covers formatting numbers with f-strings, so you can produce neatly formatted output for amounts, sequential filenames, and more. It's written for anyone searching "Python f-string number formatting".

Inside an f-string, writing {value:.2f} fixes the number of decimal places, and {value:03} pads a number with leading zeros to a fixed width. Both are handy for displaying amounts or generating sequentially numbered filenames. Remember the rule: formatting instructions go after the colon.

The sample code converts the number 1234.5 to the string "1234.50" with two decimal places using {price:.2f}, and converts the number 7 to the zero-padded, three-digit string "007" using {num:03}. You can combine various formatting specs within the same f-string framework.

A common beginner mistake is understanding what each formatting symbol means. The f in .2f stands for "floating point," and the leading 0 in 03 means "pad with zeros." Learning what each symbol does, bit by bit, unlocks much more freedom in how you display values.

Displaying a raw calculation result usually looks messy with inconsistent digit counts, so it's standard practice to apply this kind of formatting right before displaying something on screen. Adding a percent sign or a unit is just a matter of combining format specs freely to get exactly the display you want.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)