[python] How can I suppress the newline after a print statement?

I read that to suppress the newline after a print statement you can put a comma after the text. The example here looks like Python 2. How can it be done in Python 3?

For example:

for item in [1,2,3,4]:
    print(item, " ")

What needs to change so that it prints them on the same line?

This question is related to python python-3.x

The answer is


Code for Python 3.6.1

print("This first text and " , end="")

print("second text will be on the same line")

print("Unlike this text which will be on a newline")

Output

>>>
This first text and second text will be on the same line
Unlike this text which will be on a newline

Because python 3 print() function allows end="" definition, that satisfies the majority of issues.

In my case, I wanted to PrettyPrint and was frustrated that this module wasn't similarly updated. So i made it do what i wanted:

from pprint import PrettyPrinter

class CommaEndingPrettyPrinter(PrettyPrinter):
    def pprint(self, object):
        self._format(object, self._stream, 0, 0, {}, 0)
        # this is where to tell it what you want instead of the default "\n"
        self._stream.write(",\n")

def comma_ending_prettyprint(object, stream=None, indent=1, width=80, depth=None):
    """Pretty-print a Python object to a stream [default is sys.stdout] with a comma at the end."""
    printer = CommaEndingPrettyPrinter(
        stream=stream, indent=indent, width=width, depth=depth)
    printer.pprint(object)

Now, when I do:

comma_ending_prettyprint(row, stream=outfile)

I get what I wanted (substitute what you want -- Your Mileage May Vary)


There's some information on printing without newline here.

In Python 3.x we can use ‘end=’ in the print function. This tells it to end the string with a character of our choosing rather than ending with a newline. For example:

print("My 1st String", end=","); print ("My 2nd String.")

This results in:

My 1st String, My 2nd String.

print didn't transition from statement to function until Python 3.0. If you're using older Python then you can suppress the newline with a trailing comma like so:

print "Foo %10s bar" % baz,