Easy pretty printing of floats in python?
As noone has added it, it should be noted that going forward from Python 2.6+ the recommended way to do string formating is with format
, to get ready for Python 3+.
print ["{0:0.2f}".format(i) for i in a]
The new string formating syntax is not hard to use, and yet is quite powerfull.
I though that may be pprint
could have something, but I haven't found anything.
A more permanent solution is to subclass float
:
>>> class prettyfloat(float):
def __repr__(self):
return "%0.2f" % self
>>> x
[1.290192, 3.0002, 22.119199999999999, 3.4110999999999998]
>>> x = map(prettyfloat, x)
>>> x
[1.29, 3.00, 22.12, 3.41]
>>> y = x[2]
>>> y
22.12
The problem with subclassing float
is that it breaks code that's explicitly looking for a variable's type. But so far as I can tell, that's the only problem with it. And a simple x = map(float, x)
undoes the conversion to prettyfloat
.
Tragically, you can't just monkey-patch float.__repr__
, because float
's immutable.
If you don't want to subclass float
, but don't mind defining a function, map(f, x)
is a lot more concise than [f(n) for n in x]
You can do:
a = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
print ["%0.2f" % i for i in a]