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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s