Print statements without new lines in python?

2020-02-12 05:34发布

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!

标签: python
5条回答
够拽才男人
2楼-- · 2020-02-12 05:47

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.

查看更多
Deceive 欺骗
3楼-- · 2020-02-12 05:57

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.

查看更多
该账号已被封号
4楼-- · 2020-02-12 05:59

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.
查看更多
冷血范
5楼-- · 2020-02-12 06:01
import sys
for i in x:
    sys.stdout.write(i)

or

print ''.join(x)
查看更多
干净又极端
6楼-- · 2020-02-12 06:06

For Python3:

for i in x:
    print(i,end="")
查看更多
登录 后发表回答