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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With