4

How to put spaces between values in a print() statement for example:

for i in range(5):
    print(i, sep='', end='')

prints

012345

I would like it to print

0 1 2 3 4 5
6
  • 2
    Then why are you using sep=''? Commented Sep 28, 2012 at 18:50
  • remove the sep='' and try it again. Commented Sep 28, 2012 at 18:51
  • The loop isn't needed either: print(*range(5), end=''). Commented Sep 28, 2012 at 18:54
  • @StevenRumbalski: Shouldn't that be sep instead of end if they are all in one print? Commented Sep 28, 2012 at 18:55
  • 1
    @grieve: That just suppresses the newline, which behaves like his code. Commented Sep 28, 2012 at 18:57

4 Answers 4

6

While others have given an answer, a good option here is to avoid using a loop and multiple print statements at all, and simply use the * operator to unpack your iterable into the arguments for print:

>>> print(*range(5))
0 1 2 3 4

As print() adds spaces between arguments automatically, this makes for a really concise and readable way to do this, without a loop.

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

Comments

4
>>> for i in range(5):
...    print(i, end=' ')
...
0 1 2 3 4 

Explanation: the sep parameter only affects the seperation of multiple values in one print statement. But here, you have multiple print statements with one value each, so you have to specify end to be a space (per default it's newline).

Comments

1

Just add the space between quotes after the end. It should be:

end = " "

Comments

0

In Python 2.x, you could also do

for i in range(5):
    print i,

or

print " ".join(["%s"%i for i in range(5)])

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.