How can we do the basic print formatting for Python numbers?

PythonProgramming

You can format a floating number to the fixed width in Python using the format function on the string. For example,

nums = [0.555555555555, 1, 12.0542184, 5589.6654753]
for x in nums:
   print("{:10.4f}".format(x))

This will give the output

0.5556
1.0000
12.0542
5589.6655

Using the same function, you can also format integers

nums = [5, 20, 500]
for x in nums:
   print("{:d}".format(x))

This will give the output:

5
20
500

You can use it to provide padding as well, by specifying the number before d

nums = [5, 20, 500]
for x in nums:
   print("{:4d}".format(x))

This will give the output

5
20
500

The https://pyformat.info/ website is a great resource to use for learning all nuances of formatting numbers in python.

raja
Published on 20-Apr-2018 11:03:22
Advertisements