0

While thinking of a way to pretty print table header i found that integers are right aligned by default, but strings are left aligned.

For example:

>>> for i in (1,'x',0.0):
...     print("{0:5}".format(i))
... 
    1
x    
  0.0

This is easily fixed by setting alignment explicitly, but i wonder why is this so?

EDIT:

I am not looking for a way to align strings, it is easy:

>>> for i in (1,'x',0.0):
...     print("{0:>5}".format(i))
... 
    1
    x
  0.0

I just thought that all objects would be aligned the same way by deafult and i'm asking why is it not so.

1
  • 1
    I think it's just considered natural. It's the standard formatting in most spreadsheet programs, too. Commented Nov 5, 2011 at 9:55

3 Answers 3

1

Was going through the documentation. No clue what so ever for this.

Just a wild guess - We read text left-right so strings

Sign up to request clarification or add additional context in comments.

1 Comment

And we read numbers some other way? I don't think that this is related.
1

Probably you are looking for something like this

print ( "%5s" % ('x',) )
print ( "%5d" % (245,) )

which outputs

    x
  245

For the question 'why' I think an answer is that when you read some data in column you actually expect string to be left aligned

a
ab
abc

and not

   a
  ab
 abc

Also text in books is left aligned. For number most natural formatting is right aligned

  7
 45
156   

Which for istance is the way of arranging numbers for sum, subtraction and multiplication. Python choice actually reflects typographic conventions. Mixing text and numbers in a table may be considered a special case.

Comments

0

Python 3 syntax (available in 2.6, too)

>>> print("{foo:>5s}\n{bar:>5d}".format(foo="a", bar=100))
    a
  100

Read the format spec. The alignment specifier here is the >.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.