Control a print format when printing a list in Python
If you need this to work in nested structures, you should look into the pprint
module. The following should do what you want, in this context:
from pprint import PrettyPrinter
class MyPrettyPrinter(PrettyPrinter):
def format(self, object, context, maxlevels, level):
if isinstance(object, float):
return ('%.2f' % object), True, False
else:
return PrettyPrinter.format(self, object, context,
maxlevels, level)
print MyPrettyPrinter().pprint({1: [8, 1./3, [1./7]]})
# displays {1: [8, 0.33, [0.14]]}
For more details on pprint
, see: http://docs.python.org/library/pprint.html
If it's just for a flat list, then aix's solution is good. Or if you don't like the extra quotes, you could do:
print '[%s]' % ', '.join('%.3f' % val for val in list)
In [4]: print ['%5.3f' % val for val in l]
['8.364', '0.370', '0.093', '7.085', '0.469', '0.303', '9.470', '0.286', '0.229', '1.000', '9.414', '0.986', '0.534', '2.153']
where l
is your list.
edit: If the quotes are an issue, you could use
In [5]: print '[' + ', '.join('%5.3f' % v for v in l) + ']'
[8.364, 0.370, 0.093, 7.085, 0.469, 0.303, 9.470, 0.286, 0.229, 1.000, 9.414, 0.986, 0.534, 2.153]