Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map string formatting to a list of numbers

Tags:

python

Is there a way to map some thing like ".2f" % (num) to a list of numbers using the map function?

Normally to print a list of numbers I would do something like the following:

>>> a = [1.003,2.004,3.005]
>>> print " ".join(map(str, a))
1.003 2.004 3.005

But what would I put in place of the underscores to get the desired output below?

>>> print " ".join(map(____, a))
1.00 2.00 3.01

Edit

To clarify, the rounding isn't important. 3.00 works as well.

like image 219
juniper- Avatar asked Jan 21 '14 11:01

juniper-


1 Answers

a = [1.003,2.004,3.005]
print " ".join(map("{:.2f}".format, a))

Output

1.00 2.00 3.00

Note: Python, by default, rounds 3.005 to 3.00

like image 118
thefourtheye Avatar answered Sep 17 '22 22:09

thefourtheye