0

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.

4
  • 1
    have you tried "% .2f" (note: the space)? Commented Apr 6, 2014 at 11:56
  • That's the answer I was looking for! Shame I can't accept a comment. Thank you. Commented Apr 6, 2014 at 12:01
  • If you think you found an answer; you could post it and accept it. Commented Apr 6, 2014 at 12:12
  • Yes, but I wanted to give you the credit. If you post it I'll accept it, otherwise I'll do it myself. Commented Apr 6, 2014 at 16:16

4 Answers 4

2

Simply adjust the padding for positive and negative numbers accordingly:

''.join(["  %.2f" % s if s >= 0 else " %.2f" % s for s in x]).lstrip()
Sign up to request clarification or add additional context in comments.

Comments

1

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])

Comments

1

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.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.