Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How do I format numbers for a fixed width?

let's say

numbers = [ 0.7653, 10.2, 100.2325, 500.9874 ]

I'd like to output the numbers with a fixed width by varying the number of decimal places to get an output like this:

0.7653
10.200
100.23
500.98

is there an easy way to do this? I've been trying with various %f and %d configurations with no luck.

like image 552
attamatti Avatar asked Jul 25 '14 16:07

attamatti


1 Answers

Combining two str.format / format calls:

numbers = [ 0.7653, 10.2, 100.2325, 500.9874 ]
>>> for n in numbers:
...     print('{:.6s}'.format('{:0.4f}'.format(n)))
...     #  OR format(format(n, '0.4f'), '.6s')
...
0.7653
10.200
100.23
500.98

or % operators:

>>> for n in numbers:
...     print('%.6s' % ('%.4f' % n))
...
0.7653
10.200
100.23
500.98

Alternatively, you can use slicing:

>>> for n in numbers:
...     print(('%.4f' % n)[:6])
...
0.7653
10.200
100.23
500.98
like image 181
falsetru Avatar answered Oct 29 '22 08:10

falsetru