Python, print all floats to 2 decimal places in output


I need to output 4 different floats to two decimal places.

This is what I have:

print '%.2f' % var1,'kg =','%.2f' % var2,'lb =','%.2f' % var3,'gal =','%.2f' % var4,'l'

Which is very unclean, and looks bad. Is there a way to make any float in that out put '%.2f'?

Note: Using Python 2.6.

9/30/2012 2:24:00 PM

Accepted Answer

Well I would atleast clean it up as follows:

print "%.2f kg = %.2f lb = %.2f gal = %.2f l" % (var1, var2, var3, var4)
1/15/2010 10:18:30 PM

If you just want to convert the values to nice looking strings do the following:

twodecimals = ["%.2f" % v for v in vars]

Alternatively, you could also print out the units like you have in your question:

vars = [0, 1, 2, 3] # just some example values
units = ['kg', 'lb', 'gal', 'l']
delimiter = ', ' # or however you want the values separated

print delimiter.join(["%.2f %s" % (v,u) for v,u in zip(vars, units)])
Out[189]: '0.00 kg, 1.00 lb, 2.00 gal, 3.00 l'

The second way allows you to easily change the delimiter (tab, spaces, newlines, whatever) to suit your needs easily; the delimiter could also be a function argument instead of being hard-coded.

Edit: To use your 'name = value' syntax simply change the element-wise operation within the list comprehension:

print delimiter.join(["%s = %.2f" % (u,v) for v,u in zip(vars, units)])
Out[190]: 'kg = 0.00, lb = 1.00, gal = 2.00, l = 3.00'

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow