Back to: Python Programming
Format specifiers allow you to format a printed value based on the flags inserted.
The format flag is placed after the value as {value:flags}
Some flags include:
:.3f rounds a number to 3 decimal places and f assigns it as floating point
:10 allocates 10 spaces for the result to be displayed in
:010 allocates 10 spaces for the result and fills in the spaces with zeros
:< left justify
:> right justify
:^ centre align
:+ use a plus sign to indicate a positive value
:= place sign to leftmost position
: insert a space before positive numbers
:, comma separator (for thousands)
amount1 = 55.25896
amount2 = -45.26
amount3 = 1900.563
#centred, in 10 spaces, 2decimals
print(f"Amount 1: ${amount1:^10.2f}")
#right justified, 10 spaces, 0 in blanks
print(f"Amount 2: ${amount2:>010}")
#left justified, plus sign inserted, 1000's comma
print(f"Amount 3: ${amount3:<+,}")
Outputs:
Amount 1: $ 55.26
Amount 2: $0000-45.26
Amount 3: $+1,900.563
Exercise:
Using the values: amount1 = 5556.25896 amount2 = 1445.26 amount3 = 1900.264
Use format specifiers to align the financial amounts with commas to look like:
Amount 1: $ 5,556.26
Amount 2: $ 1,445.26
Amount 3: $ 1,900.26