Round, align and print list float with format ()

I need to write multiple floats to a file for which I am using the method format()

. What I want is to round off the floats to a given number of decimal places and write them at the same time.

Here's the MWE:

a = 546.35642
b = 6785.35416
c = 12.5235
d = 13.643241

line = [str('{:.2f}'.format(a)),
    str('{:.4f}'.format(b)),
    str('{:.5f}'.format(c)),
    str('{:.3f}'.format(d))]

with open('format_test.dat', "a") as f_out:
    f_out.write('''{:>10} {:>15} {:>16} {:>15}'''.format(*line))
    f_out.write('\n')

      

This gets the job done, but seems terribly confusing to me. Is there a better way to do this using format()

?

+3


source to share


1 answer


You can just add .#f

in justified format.



with open('format_test.dat', "a") as f_out:
    f_out.write('''{:>10.2f} {:>15.4f} {:>16.5f} {:>15.3f}'''.format(a, b, c, d))
    f_out.write('\n')

      

+2


source







All Articles