Print statements without newlines in python?

I was wondering if there is a way to print elements without newlines, like

x=['.','.','.','.','.','.'] for i in x: print i 

and it will print ........ instead of what it will usually print, what will

 . . . . . . . . 

Thanks!

+4
source share
5 answers

This can be easily done using print () with Python 3 .

 for i in x: print(i, end="") # substitute the null-string in place of newline 

will provide you

 ...... 

In Python v2, you can use the print() function by including:

 from __future__ import print_function 

as the first statement in the source file.

Like print () docs :

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

Please note: this is similar to a recent question I answered ( fooobar.com/questions/77123 / ... ) that contains some additional information about the print() function, if you're interested.

+15
source
 import sys for i in x: sys.stdout.write(i) 

or

 print ''.join(x) 
+9
source

I was surprised that no one mentioned the pre-Python3 method for suppressing a new line: a trailing comma.

 for i in x: print i, print # For a single newline to end the line 

This inserts spaces before certain characters, as explained here .

+6
source

As mentioned in other answers, you can print using sys.stdout.write or use a trailing comma after printing to make this space, but another way to print a list with any separator is to connect:

 print "".join(['.','.','.']) # ... print "foo".join(['.','.','.']) #.foo.foo. 
+3
source

For Python3:

 for i in x: print(i,end="") 
+1
source

All Articles