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

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

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


当前回答

为Python 2.6+使用Python 3样式打印函数(它还将打破同一文件中任何现有的带关键字的打印语句)。

# For Python 2 to use the print() function, removing the print keyword
from __future__ import print_function
for x in xrange(10):
    print('.', end='')

为了不破坏所有Python 2打印关键字,请创建一个单独的printf.py文件:

# printf.py

from __future__ import print_function

def printf(str, *args):
    print(str % args, end='')

然后,在文件中使用它:

from printf import printf
for x in xrange(10):
    printf('.')
print 'done'
#..........done

显示printf样式的更多示例:

printf('hello %s', 'world')
printf('%i %f', 10, 3.14)
#hello world10 3.140000

其他回答

您可以尝试:

import sys
import time
# Keeps the initial message in buffer.
sys.stdout.write("\rfoobar bar black sheep")
sys.stdout.flush()
# Wait 2 seconds
time.sleep(2)
# Replace the message with a new one.
sys.stdout.write("\r"+'hahahahaaa             ')
sys.stdout.flush()
# Finalize the new message by printing a return carriage.
sys.stdout.write('\n')

其中许多答案似乎有点复杂。在Python 3.x中,您只需执行以下操作:

print(<expr>, <expr>, ..., <expr>, end=" ")

end的默认值为“\n”。我们只是将其更改为空格,或者您也可以使用end=“”(无空格)来执行printf通常所做的操作。

如何在同一行打印:

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

你想在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

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