Finding field widths of floats for neat printing
Steven Taschuk
staschuk at telusplanet.net
Thu Apr 3 23:28:25 EST 2003
Quoth Andrew Gregory:
> I want to write lists of floating point numbers to text files in neat
> columns with decimal points aligned, right-hand edges straight (rather
> than ragged), and without unnecessary trailing zeros, e.g.
> 1.1 -34.67 0.006
> 2.0 -1.05 0.010
> etc.
[...]
How about this?
def strparts(value):
s = ('%f' % value).rstrip('0').split('.')
if len(s) < 2:
s.append('')
return s
def formatfor(values):
leftparts, rightparts = zip(*map(strparts, values))
leftwidth = max(map(len, leftparts))
precision = max(map(len, rightparts))
width = leftwidth + precision
if precision:
width += 1 # decimal point
return '%%%d.%df' % (width, precision)
table = [[1.1, -34.67, 0.006], [2, -1.05, 0.01]]
formats = map(formatfor, zip(*table))
for row in table:
for fmt, val in zip(formats, row):
print fmt % val,
print
Output:
1.1 -34.67 0.006
2.0 -1.05 0.010
--
Steven Taschuk 7\ 7'Z {&~ .
staschuk at telusplanet.net Y r --/hG-
(__/ )_ 1^1`
More information about the Python-list
mailing list