How can I suppress a new line after a print statement?

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

For example:

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

What needs to be changed so that it prints them on one line?

+42
python
Aug 24 '12 at 3:23
source share
4 answers

The question asks the question: " How to do this 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 the Python doc for more information:

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

-

Besides

In addition, the print() function also offers the sep parameter, which allows you to specify how the individual elements to be printed should be separated. For example.

 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 
+78
Aug 24 '12 at 3:24
source share

print did not go from statement to function until Python 3.0. If you are using older Python, you can suppress a new line with a trailing comma, for example:

 print "Foo %10s bar" % baz, 
+4
Apr 21 '15 at 19:08
source share

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") 

Exit

 >>> This first text and second text will be on the same line Unlike this text which will be on a newline 
+2
Apr 03 '17 at 17:02 on
source share

Since the python 3 print () function allows you to define end = "", which satisfies most of the questions.

In my case, I wanted PrettyPrint and was disappointed that this module was not updated so much. Therefore, I made it so that 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 this:

 comma_ending_prettyprint(row, stream=outfile) 

I get what I wanted (replace what you want - your May run may)

0
Feb 03 '16 at 7:16
source share



All Articles