Shakiib
Shakiib

Reputation: 57

how to add a space before a line in python

I want to print 2 space before every line of my code's output.
My code:

n = int(input())
for row in range(1, n+1):
    for column in range(1, n+1):
        print(column, end='   ')
    print('')


input:

5

My output:

1   2   3   4   5
1   2   3   4   5
1   2   3   4   5
1   2   3   4   5
1   2   3   4   5

The output I want:

  1   2   3   4   5
  1   2   3   4   5
  1   2   3   4   5
  1   2   3   4   5
  1   2   3   4   5

Upvotes: 1

Views: 1432

Answers (3)

bhristov
bhristov

Reputation: 3197

Try this:

n = int(input())
for row in range(1, n+1):
    for column in range(1, n+1):
        print('  ',column, end=' ') # we print some whitespace in front of every character and at the end.
    print('')

This code prints 2 spaces before and 1 space after, like the output that you want.

Upvotes: 1

Mazziotti Raffaele
Mazziotti Raffaele

Reputation: 411

You can use the join method for strings:

n = int(input())
for row in range(1, n+1):
    print( "  " + "  ".join([str(x) for x in range(1, n+1)]) )

Upvotes: 0

match
match

Reputation: 11070

You can achieve this by putting the whitespace in before the column value:

n = int(input())
for row in range(1, n+1):
    for column in range(1, n+1):
        print('    ', column, end='')
    print()

This also removes the extra whitespace that your existing solution puts on the end of each line (though if you wanted that back, simple add more space to the 2nd print - i.e. print(' '))

Upvotes: 0

Related Questions