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

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

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


当前回答

只需使用end=“”或sep=“”

>>> for i in range(10):
        print('.', end = "")

输出:

.........

其他回答

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

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

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上测试过。

如何在同一行打印:

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

蟒蛇3:

print('Hello',end='')

例子:

print('Hello',end=' ')
print('world')

输出:你好,世界

此方法在提供的文本之间添加sperator:

print('Hello','world',sep=',')

输出:你好,世界

只需使用end=“”或sep=“”

>>> for i in range(10):
        print('.', end = "")

输出:

.........

注意:这个问题的标题以前类似于“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
..........