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


let's

numbers = [ 0.7653, 10.2, 100.2325, 500.9874 ] 

i'd output numbers fixed width varying number of decimal places output this:

0.7653 10.200 100.23 500.98 

is there easy way this? i've been trying various %f , %d configurations no luck.

combining 2 str.format / format calls:

numbers = [ 0.7653, 10.2, 100.2325, 500.9874 ] >>> 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:

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

alternatively, can use slicing:

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

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

.htaccess - ERR_TOO_MANY_REDIRECTS htaccess -