1

I am trying to understand the behavior of the code below. When I increase the number in the first curly braces, I get extra whitespace to the left of the first column. When I do it for the second number, I also get extra whitespace, but to the left of the second column. However, when I do it for the third one, nothing changes. Why?

w = ['storm', 'ubuntu', 'singular', 'pineapple']
for i, word in enumerate(w):
    word_index = 3
    print('{:2} {:1} {:6}'.format(i, word_index, word))

2 Answers 2

3

Numbers pad left by default, but strings pad right (docs):

>>> "{:3}".format(1)
'  1'
>>> "{:3}".format("1")
'1  '

If you want the string to align right too, specify it:

>>> "{:>3}".format("1")
'  1'

Note that "storm" (length 5) does actually get an extra trailing space when padded to width 6, but since it was printed on the right you probably wouldn't notice.

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

Comments

1

Something actually does change, but you cannot see it. Let's use a slightly modified version of your code, that marks the margins of the output:

w = ['storm', 'ubuntu', 'singular', 'pineapple']
for i, word in enumerate(w):
    word_index = 3
    print('>>{:2} {:1} {:6}<<'.format(i, word_index, word))

When you run this, you'll get:

>> 0 3 storm <<
>> 1 3 ubuntu<<
>> 2 3 singular<<
>> 3 3 pineapple<<

Now, let's change the third width to 16:

w = ['storm', 'ubuntu', 'singular', 'pineapple']
for i, word in enumerate(w):
    word_index = 3
    # Changed width of 3rd field from 6 to 16
    print('>>{:2} {:1} {:16}<<'.format(i, word_index, word))

Running this will give more white space after the last field:

>> 0 3 storm           <<
>> 1 3 ubuntu          <<
>> 2 3 singular        <<
>> 3 3 pineapple       <<

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.