68

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?

Community
  • 1
  • 1
Ci3
  • 4,632
  • 10
  • 34
  • 44
  • 1
    You could just do `print(' '.join([str(i) for i in [1, 2, 3, 4]]))` – anon582847382 Mar 22 '14 at 23:34
  • 1
    `print(*[1, 2, 3, 4])` works for the common case of printing a space separated sequence – John La Rooy Mar 18 '15 at 16:36
  • 1
    Related post - [How to print without newline or space?](https://stackoverflow.com/q/493386/465053). The accepted answer in this thread covers all Python versions. – RBT Jul 23 '18 at 10:03

5 Answers5

110

The question asks: "How can it be done in Python 3?"

Use this construct with Python 3.x:

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

This will generate:

1  2  3  4

See this Python doc for more information:

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

--

Aside:

in addition, the print() function also offers the sep parameter that lets one specify how individual items to be printed should be separated. E.g.,

In [21]: print('this','is', 'a', 'test')  # default single space between items
this is a test

In [22]: print('this','is', 'a', 'test', sep="") # no spaces between items
thisisatest

In [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separation
this--*--is--*--a--*--test
Levon
  • 138,105
  • 33
  • 200
  • 191
  • 3
    Perfect! So end="" just overrides the newline character. – Ci3 Aug 24 '12 at 03:29
  • @ChrisHarris See the update with the quote from the docs, so you are replacing the newline with `""` (the empty string) – Levon Aug 24 '12 at 03:30
  • Everywhere I look everyone says to do end='', but I get: SyntaxError: invalid syntax – thang May 03 '15 at 06:05
  • @thang What version of Python are you using? This works for version 3.x – Levon May 03 '15 at 12:07
  • @Levon, 2.7. Probably a version issue, but I need backwards compatibility :( Guess I am stuck with sys.stdout.write – thang May 11 '15 at 07:39
  • @thang You might want to look at the "from future import print", not sure that will fix your problem, but it just might http://python-future.org/quickstart.html and http://stackoverflow.com/questions/7075082/what-is-future-in-python-used-for-and-how-when-to-use-it-and-how-it-works – Levon May 11 '15 at 19:43
  • 3
    To be more specific, it's `from __future__ import print_function`. – Scott Stafford May 20 '15 at 15:46
  • @ScottStafford Good point, thanks for helping point out that detail – Levon May 20 '15 at 21:09
5

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
Jasmohan
  • 237
  • 3
  • 5
4

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,
0

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)

neil.millikin
  • 1,077
  • 1
  • 10
  • 15
0

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.
nw79
  • 1