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.
只需相应地调整正数和负数的填充即可:
''.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.
have you tried "% .2f"
(note: the space)? – JF Sebastian
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.