Printing a list of right justified separated numbers with no trailing space in python

99 Views Asked by At
for i in range(7):
    print("{0:>2}".format(i), sep = " ", end="")

My sep = " " is not being taken into account. I do not want to use str.join(), and I would prefer to not have to create and add to a string each time the loop is run.

Please help me solve!

1

There are 1 best solutions below

1
On

You code has multiple problems. The { outside the format string is a syntax error. You need a pair {} in the format string. You should use conversion type d for an int. Sep only applies if there is more than one field. End determines what is printed after each print statement. I expect the following is what you want.

for i in range(7):
    print("{0:>2d}".format(i), end=" ")
# prints
 0  1  2  3  4  5  6 

EDIT: Avoiding a final space is only slightly harder.

start = True
for i in range(7):
    print('' if start else ' ', "{0:>2d}".format(i), sep='', end='')
    start = False
# prints
 0  1  2  3  4  5  6