Question

So far, I've got:

x=[0.0, 1.2135854798749774, 1.0069824713281044, 0.5141246736157659, -0.3396344921640888, -0.33926090064512615, 0.4877599543804152, 0.0]

print ' '.join(["%.2f" % s for s in x])

which produces:

0.00 1.21 1.01 0.51 -0.34 -0.34 0.49 0.00

the problem being that -0.34 is one character longer than 0.51, which produces ragged left edges when printing several lists.

Any better ideas?

I'd like:

0.00 1.21 1.01 0.51 -0.34 -0.34 0.49 0.00
0.00 1.21 1.01 0.51 0.34 0.34 0.49 0.00
0.00 1.21 -1.01 -0.51 -0.34 -0.34 -0.49 0.00

to turn into:

0.00 1.21  1.01  0.51 -0.34 -0.34  0.49 0.00
0.00 1.21  1.01  0.51  0.34  0.34  0.49 0.00
0.00 1.21 -1.01 -0.51 -0.34 -0.34 -0.49 0.00

and it would be even nicer if there was some built in or standard library way of doing this, since print ' '.join(["%.2f" % s for s in x]) is quite a lot to type.

Was it helpful?

Solution 4

have you tried "% .2f" (note: the space)? – J.F. Sebastian

OTHER TIPS

Simply adjust the padding for positive and negative numbers accordingly:

''.join(["  %.2f" % s if s >= 0 else " %.2f" % s for s in x]).lstrip()

Use rjust or ljust:

x=[0.0, 1.2135854798749774, 1.0069824713281044, 0.5141246736157659, -0.3396344921640888, -0.33926090064512615, 0.4877599543804152, 0.0]

print ' '.join([("%.2f"%s).ljust(5) for s in x])

try this: print ' '.join(["%5.2f" % s for s in x]), the number 5 in the string "%5.2f" specifies the maximum field width. It is compatible to the conversion specification in C.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top