7

我想知道是否有一种方法可以打印没有换行符的元素,例如

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

for i in x:
    print i

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

.
.
.
.
.
.
.
.

谢谢!

4

5 回答 5

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() 文档所述:

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

请注意,这类似于我最近回答的一个问题 ( https://stackoverflow.com/a/12102758/1209279print() ),如果您好奇的话,其中包含有关该函数的一些附加信息。

于 2012-08-25T17:14:15.040 回答
9
import sys
for i in x:
    sys.stdout.write(i)

或者

print ''.join(x)
于 2012-08-25T17:12:01.927 回答
6

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

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

这确实会在某些字符之前插入空格,如此处所述

于 2012-08-25T20:10:16.050 回答
3

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

print "".join(['.','.','.'])
# ...
print "foo".join(['.','.','.'])
#.foo.foo.
于 2012-08-25T17:16:17.013 回答
1

对于 Python3:

for i in x:
    print(i,end="")
于 2012-08-25T17:15:14.050 回答