A
A
alekseishaklov2021-11-11 20:02:55
Python
alekseishaklov, 2021-11-11 20:02:55

Why is there an extra space at the beginning of a line?

There is the following simple python code:

x = int(input())
b = ""
for i in range(0, x + 1):
    b += " " + str(i)
print(b)

Question: why did an extra space appear at the beginning of the line, and how to get rid of it without losing spaces in the middle of the line?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-11-11
@alekseishaklov

Obviously there is no need to add a space in the first iteration. Besides, incrementing a string in a loop is bad practice. Yes, and in general it can be done easier:

x = int(input())
print(' '.join(str(i) for i in range(0, x + 1)))

or even
x = int(input())
print(*range(x+1), sep=' ')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question