# Example: Formatting print(format(0.12345, '.3f')) print(format(12345678, '3.7f')) # format as part of string print("number1 = %5d, number2 = %8.2f" % (123, 98765.4321)) # using print with a modulo operator, 123 is assigned to %5d # and 98765.4321 is assigned to %8.2f # notice that number1 is formatted with 5 placeholder (= 5 charcters) # since the 123 consists only 3 digits, # the output is padded with 2 leading spaces # number2 is formatted with 8 placeholders of which 2 is for precision print("number1 = %5d, number2 = %3.2f" % (123, 98765.4321)) # format() is a function that works on a string # use format() to indicate how many decimals # a floating point number should be displayed # by placing a period and an integer to the left of the f # format() will round the parameter to the requested # number of decimals print("{:.2f}".format(98765.4321)) print("{:.3f}".format(98765.4321)) # specify 3 placeholders, if given number is shorter than 3 characters # pad it with leading spaces print("{:3d}".format(123456)) # specify 10 placeholders, if the given number is shorter than 3 characters # pad it with leading spaces print("{:10d}".format(123456)) # specify 10 decimals, if the given number has shorter decimal # pad it with ending spaces print("{:.10f}".format(123.456))