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
  • 4,418
  • 9
  • 35
  • 58

5 Answers5

18

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
  • 138,105
  • 33
  • 200
  • 191
  • 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,926
  • 2
  • 23
  • 34
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
  • 497,756
  • 71
  • 530
  • 681
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
  • 90,542
  • 19
  • 167
  • 203
1

For Python3:

for i in x:
    print(i,end="")
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284