Formatting options

Hi everyone,

I have as quick question. In this code
print( 'Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)')
I get the 1 & 2 are for decimals but what the 5 is for?

Thanks :blush: :blush:

The 5.2f sets the minimum field with to 5 and the number of digits after the decimal place to 2.

So the output will be padded with spaces on the left hand side to give a total width of at least 5:

'{:5.2f}'.format(1.5)  # returns ' 1.50' with a leading space
'{:5.2f}'.format(100.5)  # returns '100.50'
1 Like

Many thanks for your help :+1: :+1:

For ‘coding exercise’, I’m working my way through an old book I have, converting the examples therein, into Python3 code.

This script, is a good demonstration of the formatting that you asked about.


#from page 8: The C Programming Language by K&R

#:- Print a table of Fahrenheit temperatures and their centigrade or Celsius equivalents
#:- using this formula {C = (5/9)(F-32)} and a step size of 20

lower = 0
upper = 300
step = 20

fahr = lower

while fahr <= upper:
    celsius = (5.0/9.0) * (fahr-32.0)
    print(f"{fahr:4.0f} {celsius:6.1f}")
    fahr += step

To paraphrase from said book…

{fahr:4.0f} says that a floating point number is to be printed in a space at least four characters wide, with no digits after the decimal point. {celsius:6.1f} describes another number to occupy at least six spaces, with one digit after the decimal point.

1 Like