Easy pretty printing of floats?
It's an old question but I'd add something potentially useful:
I know you wrote your example in raw Python lists, but if you decide to use numpy
arrays instead (which would be perfectly legit in your example, because you seem to be dealing with arrays of numbers), there is (almost exactly) this command you said you made up:
import numpy as np
np.set_printoptions(precision=2)
Or even better in your case if you still want to see all decimals of really precise numbers, but get rid of trailing zeros for example, use the formatting string %g
:
np.set_printoptions(formatter={"float_kind": lambda x: "%g" % x})
For just printing once and not changing global behavior, use np.array2string
with the same arguments as above.
Printing a formatted Float list in Python3
you are trying to format a list
with the format string .2f
- what you want is to format the float
s inside your list. this is one way to fix that:
Q = [1.3, 2.4]
print(', '.join('{:.2f}'.format(f) for f in Q))
# 1.30, 2.40
starting from python 3.6 this could also be written as:
print(', '.join(f'{q:.2f}' for q in Q))
alternatively you could create you own class that accepts format strings:
class FloatList(list):
def __init__(self, *args):
super().__init__(args)
def __format__(self, format_spec):
return f'[{", ".join(f"{i:{format_spec}}" for i in self)}]'
fl = FloatList(0.1, 0.33, 0.632)
print(f"{fl:.2f}") # [0.10, 0.33, 0.63]
Pretty printing a list of list of floats?
you can right-pad like this:
str = '%-10f' % val
to left pad:
set = '%10f' % val
or in combination pad and set the precision to 4 decimal places:
str = '%-10.4f' % val
:
import sys
rows = [[1.343, 348.222, 484844.3333], [12349.000002, -2.43333]]
for row in rows:
for val in row:
sys.stdout.write('%20f' % val)
sys.stdout.write("\n")
1.343000 348.222000 484844.333300
12349.000002 -2.433330
pprint with custom float formats
As you said, you can achieve this by subclassing PrettyPrinter
and overwriting the format
method. Note that the output is not only the formatted string, but also some flags.
Once you're at it, you could also generalize this and pass a dictionary with the desired formats for different types into the constructor:
class FormatPrinter(pprint.PrettyPrinter):
def __init__(self, formats):
super(FormatPrinter, self).__init__()
self.formats = formats
def format(self, obj, ctx, maxlvl, lvl):
if type(obj) in self.formats:
return self.formats[type(obj)] % obj, 1, 0
return pprint.PrettyPrinter.format(self, obj, ctx, maxlvl, lvl)
Example:
>>> d = {('A', 'B'): {'C': 0.14285714285714285,
... 'D': 0.14285714285714285,
... 'E': 0.14285714285714285},
... 'C': 255}
...
>>> FormatPrinter({float: "%.2f", int: "%06X"}).pprint(d)
{'C': 0000FF,
('A', 'B'): {'C': 0.14,
'D': 0.14,
'E': 0.14}}
Python, print all floats to 2 decimal places in output
Well I would atleast clean it up as follows:
print "%.2f kg = %.2f lb = %.2f gal = %.2f l" % (var1, var2, var3, var4)
Printing floats and strings in one line
I'm guessing this is Python 3, but since it isn't tagged with a language that is my best guess.
You just need to cast hours_worked and compute back into the string type from the float type, like so:
print ('You worked' + str(hours_worked) + 'and your pay is' + str(compute))
Formatting floats without trailing zeros
Me, I'd do ('%f' % x).rstrip('0').rstrip('.')
-- guarantees fixed-point formatting rather than scientific notation, etc etc. Yeah, not as slick and elegant as %g
, but, it works (and I don't know how to force %g
to never use scientific notation;-).
Printing formatted floats in nested tuple of mixed type
This is not exactly what you need, but very close, and the code is pretty compact.
def truncateFloat(data):
return tuple( ["{0:.4}".format(x) if isinstance(x,float) else (x if not isinstance(x,tuple) else truncateFloat(x)) for x in data])
pprint(truncateFloat(the_list))
For your example the result is
(('520', ('0.267', '9.531e-22', 1431, ('0.2182', '0.3145'), 11981481)),
('1219', ('0.2776', '2.023e-25', 1431, ('0.229', '0.3247'), 14905481)))
You can play with options of .format()
to get what you want.
Format float while printing dict
You can loop on the keys of the dictionary to print each value (or combine them into one string to print).
You can loop on each key with :
for key in dictio.keys():
print (key, "{:.2f}".format(dictio[key]))
Related Topics
How to Run All Python Unit Tests in a Directory
How to Make Two Plots Side-By-Side Using Python
Checking If All Elements in a List Are Unique
Running Infinite Loops Using Threads in Python
What Is the Reason for Having '//' in Python
Select Pandas Rows Based on List Index
I Can't Seem to Get --Py-Files on Spark to Work
Underscore VS Double Underscore with Variables and Methods
Find the Most Frequent Number in a Numpy Array
Round Number to Nearest Integer
How to Plot Nan Values as a Special Color with Imshow in Matplotlib
Removing Index Column in Pandas When Reading a CSV
Differencebetween Encode/Decode
Installing Python Packages Without Internet and Using Source Code as .Tar.Gz and .Whl
N-Grams in Python, Four, Five, Six Grams
Multiple Levels of 'Collection.Defaultdict' in Python
How to Convert Strings in a Pandas Data Frame to a 'Date' Data Type