考虑在Python中使用print的以下示例:

>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .

在每个值之间添加换行符或空格。我怎样才能避免这种情况,从而使输出。。。。相反换句话说,如何将字符串“附加”到标准输出流?


当前回答

你会注意到以上所有答案都是正确的。但我想做一个捷径,始终在结尾处写入“end=''”参数。

您可以定义如下函数

def Print(*args, sep='', end='', file=None, flush=False):
    print(*args, sep=sep, end=end, file=file, flush=flush)

它将接受所有数量的参数。甚至它也会接受所有其他参数,如file、flush等,并使用相同的名称。

其他回答

在Python2.x中,您可以在print函数的末尾添加,这样它就不会在新行上打印了。

我最近也有同样的问题。。。

我通过以下方式解决了这个问题:

import sys, os

# Reopen standard output with "newline=None".
# in this mode,
# Input:  accepts any newline character, outputs as '\n'
# Output: '\n' converts to os.linesep

sys.stdout = os.fdopen(sys.stdout.fileno(), "w", newline=None)

for i in range(1,10):
    print(i)

这在Unix和Windows上都有效,但我还没有在Mac OS X上测试过。

只需使用end=''

for i in range(5):
  print('a',end='')

# aaaaa

注意:这个问题的标题以前类似于“How to printf in Python”

由于人们可能会根据标题来这里寻找它,Python也支持printf样式替换:

>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
...     print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three

而且,您可以方便地相乘字符串值:

>>> print "." * 10
..........

如何在同一行打印:

import sys
for i in xrange(0,10):
   sys.stdout.write(".")
   sys.stdout.flush()