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

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

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


当前回答

或具有如下功能:

def Print(s):
    return sys.stdout.write(str(s))

现在:

for i in range(10): # Or `xrange` for the Python 2 version
    Print(i)

输出:

0123456789

其他回答

你想在for循环中打印一些东西;但你不希望每次都用新的行打印。。。

例如:

 for i in range (0,5):
   print "hi"

 OUTPUT:
    hi
    hi
    hi
    hi
    hi

但你希望它像这样打印:嗨嗨嗨嗨对吗????

只需在打印“hi”后添加逗号。

例子:

for i in range (0,5):
    print "hi",

输出:

hi hi hi hi hi

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

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

输出:

.........

对于Python 2和更早版本,它应该像Re中描述的那样简单:没有CR如何打印?作者:Guido van Rossum(意译):

是否可以打印某些内容,但不能自动生成是否附加回车?

是的,在要打印的最后一个参数后附加逗号。例如,此循环将数字0..9打印在由空格分隔的行上。请注意添加最后一行的无参数“print”:

>>> for i in range(10):
...     print i,
... else:
...     print
...
0 1 2 3 4 5 6 7 8 9
>>>

Python 3:

print('.', end='')

Python 2.6+:

from __future__ import print_function # needs to be first statement in file
print('.', end='')

Python<=2.5:

import sys
sys.stdout.write('.')

如果每次打印后都有多余的空间,在Python 2中:

print '.',

Python 2中的误导-避免:

print('.'), # Avoid this if you want to remain sane
# This makes it look like print is a function, but it is not.
# This is the `,` creating a tuple and the parentheses enclose an expression.
# To see the problem, try:
print('.', 'x'), # This will print `('.', 'x') `

如何在同一行打印:

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