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

by
Share this Article: Facebook65Google+0Twitter9LinkedIn0Reddit0StumbleUpon1

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

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

print(“Hello”)
print(“world”)

[/cc]

The output is going to be in two separated lines:

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

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=’ ‘)
print(“world”)[/cc]

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=’ ‘)
print(“world”)[/cc]

and the output will be in the same line

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

For questions please refer to our Q/A forum at : http://ask.unixmen.com/

Share this Article: Facebook65Google+0Twitter9LinkedIn0Reddit0StumbleUpon1