Grey
Grey

Reputation: 45

Missing whitespace when printing in a loop

I have this strange problem when following a reference, this code:

for r in range(10):
    for c in range(r):
        print "",
    for c in range(10-r):
        print c,
    print ""

should print out something like this:

    0 1 2 3 4 5 6 7 8 9 
      0 1 2 3 4 5 6 7 8 
        0 1 2 3 4 5 6 7
          0 1 2 3 4 5 6
            0 1 2 3 4 5
              0 1 2 3 4
                0 1 2 3
                  0 1 2
                    0 1
                      0

but Instead I am getting this:

0 1 2 3 4 5 6 7 8 9 
 0 1 2 3 4 5 6 7 8 
  0 1 2 3 4 5 6 7 
   0 1 2 3 4 5 6 
    0 1 2 3 4 5 
     0 1 2 3 4 
      0 1 2 3 
       0 1 2 
        0 1 
         0

Can anyone explain to me what is causing in indent on right side, it seems so simple but I have no clue what I can do to fix this?

Upvotes: 0

Views: 968

Answers (3)

Nick T
Nick T

Reputation: 26717

If you want to format it just so, it might be better to just let Python do it for you instead of counting explicit and the hidden implicit spaces. See the string formatting docs for what {:^19} means and more.

for i in range(10):
    nums = ' '.join(str(x) for x in range(10 - i))
    #print '{:^19}'.format(nums) # reproduces your "broken" code
    print '{:>19}'.format(nums) # your desired output

Using the print function is a good alternative sometimes, as you can eliminate hidden spaces by setting the keyword argument end to an empty string:

from __future__ import print_function # must be at the top of the file.
# ...
print(x, end='')

Upvotes: 1

PaulMag
PaulMag

Reputation: 4148

You are simply not creating enough indent on the left side (there is no such thing as right side indent while printing).

For every new line you want to increase the indent by two spaces, because you are adding a number+whitespace on the line above. "", automatically adds one whitespace (this is why there is whitespaces between the numbers). Since you need to add two, simply add a whitespace within the quotes, like this: " ",.

The extra whitespace is filling the space of the number in the line above. The comma in "", is only filling the space between the numbers. To clarify: " ", uses the same space as c,, two characters, while "", only uses one character.

Here is your code with the small fix:

for r in range(10):
    for c in range(r):
        print " ", # added a whitespace here for correct indent
    for c in range(10-r):
        print c,
    print ""

Upvotes: 0

You were printing the leading spaces incorrectly. You were printing empty quotes ("") which is printing only a single space. When you do print c, there is a space printed after c is printed. You should print " " instead to get the correct spacing. This is a very subtle thing to notice.

for r in range(10):
    for c in range(r):
        print " ", #print it here
    for c in range(10-r):
        print c,
    print ""

Test

Upvotes: 1

Related Questions