7

I was wondering if there is a way to print elements without newlines such as

x=['.','.','.','.','.','.']

for i in x:
    print i

and that would print ........ instead of what would normally print which would be

.
.
.
.
.
.
.
.

Thanks!

ollien
  • 3,946
  • 9
  • 32
  • 55

5 Answers5

17

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

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

will give you

......

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

from __future__ import print_function

as the first statement in your source file.

As the print() docs state:

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

Note, this is similar to a recent question I answered ( https://stackoverflow.com/a/12102758/1209279 ) that contains some additional information about the print() function if you are curious.

Community
  • 1
  • 1
Levon
  • 129,246
  • 33
  • 194
  • 186
  • 1
    Note that this will only work in Python 3 or when you have `from __future__ import print_function` at the beginning of your file. – omz Aug 25 '12 at 17:15
  • @omz Yes that is correct - I was just adding a note about that while you were posting your comment. – Levon Aug 25 '12 at 17:17
9
import sys
for i in x:
    sys.stdout.write(i)

or

print ''.join(x)
applicative_functor
  • 4,706
  • 2
  • 20
  • 33
6

I surprised no one has mentioned the pre-Python3 method for suppressing the newline: a trailing comma.

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

This does insert spaces before certain characters, as is explained here.

chepner
  • 446,329
  • 63
  • 468
  • 610
3

As mentioned in the other answers, you can either print with sys.stdout.write, or using a trailing comma after the print to do the space, but another way to print a list with whatever seperator you want is a join:

print "".join(['.','.','.'])
# ...
print "foo".join(['.','.','.'])
#.foo.foo.
jdi
  • 87,105
  • 19
  • 159
  • 196
1

For Python3:

for i in x:
    print(i,end="")
Burhan Khalid
  • 161,711
  • 18
  • 231
  • 272