在python中没有新行的打印语句?

时间:2012-08-25 17:10:36

标签: python

我想知道是否有办法打印没有换行符的元素,例如

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

for i in x:
    print i

这将打印........而不是通常打印的

.
.
.
.
.
.
.
.

谢谢!

5 个答案:

答案 0 :(得分:17)

使用 Python 3 print() 功能可以轻松完成此操作。

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

会给你

......

Python v2 中,您可以使用print()功能,包括:

from __future__ import print_function

作为源文件中的第一个语句。

作为print() docs州:

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

请注意,这与我最近回答的问题(https://stackoverflow.com/a/12102758/1209279)类似,如果您感到好奇,它会包含有关print()功能的一些其他信息。

答案 1 :(得分:9)

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

print ''.join(x)

答案 2 :(得分:6)

我很惊讶没有人提到用于抑制换行符的pre-Python3方法:一个尾随的逗号。

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

这会在某些字符之前插入空格,如here所述。

答案 3 :(得分:3)

正如其他答案中所提到的,您可以使用sys.stdout.write进行打印,也可以在打印后使用尾随逗号来执行空格,但是使用您想要的任何分隔符打印列表的另一种方法是连接:

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

答案 4 :(得分:1)

对于Python3:

for i in x:
    print(i,end="")
相关问题