Python: avoid new line with print command

Javicobos picture Javicobos · Jun 29, 2012 · Viewed 425.2k times · Source

I've started programming today and have this issue with Python. It's pretty dumb but I can't figure out how to do it. When I use the print command, it prints whatever I want and then goes to a different line. For example:

print "this should be"; print "on the same line"

Should return:

this should be on the same line

but instead returns:

this should be
on the same line

More precisely I was trying to create a program with if that told me whether a number was a 2 or not

def test2(x):
    if x == 2:
        print "Yeah bro, that's tottaly a two"
    else:
        print "Nope, that is not a two. That is a (x)"

But it doesn't recognise the last (x) as the value entered, and rather prints exactly: "(x)" (the letter with the brackets). To make it work I have to write:

print "Nope, that is not a two. That is a"; print (x)

And if e.g. I enter test2(3) that gives:

Nope, that is not a two, that is a
3

So either i need to make Python recognise my (x) inside a print line as the number; or to print two separate things but on the same line. Thanks in advance and sorry for such a stupid question.

IMPORTANT NOTE: I am using version 2.5.4

Another note: If i put print "Thing" , print "Thing2" it says "Syntax error" on the 2nd print.

Answer

Sven Marnach picture Sven Marnach · Jun 29, 2012

In Python 3.x, you can use the end argument to the print() function to prevent a newline character from being printed:

print("Nope, that is not a two. That is a", end="")

In Python 2.x, you can use a trailing comma:

print "this should be",
print "on the same line"

You don't need this to simply print a variable, though:

print "Nope, that is not a two. That is a", x

Note that the trailing comma still results in a space being printed at the end of the line, i.e. it's equivalent to using end=" " in Python 3. To suppress the space character as well, you can either use

from __future__ import print_function

to get access to the Python 3 print function or use sys.stdout.write().