Printing Without a Newline in Python

Printing Without a Newline in Python

In Python 2.x.x, we could use:

>>> for i in range(10):
…     print “*”,

And we see the result:

* * * * * * * * * *

However, Python 3.x.x is slightly different as to the comma use:

>>> for i in range(10):
…     print(“*”)

*
*
*
*
*
*
*
*
*
*
>>> for i in range(10):
…     print(“*”,)

*
*
*
*
*
*
*
*
*
*
>>> for i in range(10):
…     print(“*,”)

*,
*,
*,
*,
*,
*,
*,
*,
*,
*,
>>> for i in range(10):
…     print(“*”),

*
(None,)
*
(None,)
*
(None,)
*
(None,)
*
(None,)
*
(None,)
*
(None,)
*
(None,)
*
(None,)
*
(None,)
>>>

In Python 3.x.x, we have no way to get

* * * * * * * * * *

using the print() function and the comma. We need do something else:

>>> for i in range(10):
…     print(“*”, end=”)

One space between ‘ and ‘ after end=.

And the result:
**********

It works. We have 10 asterisks in one line (without \n behind each of them) like before. But the result isn’t exactly the same. There should be spaces among those asterisks. We need do something else.

>>> for i in range(10):
…     print(“*”, end=’ ‘)

Two spaces between ‘ and ‘ after end=.

And the result:
* * * * * * * * * *

Now we are happy.

Leave a comment