How to print in the same line using end=’ ‘ argument

The print statement prints by default a newline character in Python. Look this example:

[cc escaped=”true” lang=”python”]



The output is going to be in two separated lines:

[cc escaped=”true” lang=”python”]Hello

If you want to avoid this and use multiple print statements but print in the same line, you have to explicitly tell Python to end its print statement with an empty string instead of a newline character. To do this, you have to add a second argument end=’ ‘ which tells Python to end the print statement with an empty string.

If you are using Python 2.x you are most likely end up with a SyntaxError like this one:

Screen Shot 2013-09-30 at 8.12.29 PM

This error occurs because print statement is not implemented as a function.

So, if you are using Python 2.x, you need to fix this error by telling Python to use a print statement as a function. To do this, add this line of code before anything else:

[cc escaped=”true” lang=”python”]
from __future__ import print_function[/cc]

Now, your file looks like this:

[cc escaped=”true” lang=”python”]

from __future__ import print_function
print(“Hello”, end=’ ‘)

If you’re using Python 3 then you don’t have to use from __future__ import print_function because print() is implemented as a function already.

[cc escaped=”true” lang=”python”]

print(“Hello”, end=’ ‘)

and the output will be in the same line

[cc escaped=”true” lang=”python”]Hello world[/cc]