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

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

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


当前回答

您可以尝试:

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')

其他回答

您可以尝试:

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中,可以使用print函数的sep=和end=参数:

要不在字符串末尾添加换行符,请执行以下操作:

print('.', end='')

要在要打印的所有函数参数之间不添加空格,请执行以下操作:

print('a', 'b', 'c', sep='')

您可以将任何字符串传递给任一参数,并且可以同时使用两个参数。

如果缓冲有问题,可以通过添加flush=True关键字参数来刷新输出:

print('.', end='', flush=True)

Python 2.6和2.7

从Python 2.6中,您可以使用__future__模块从Python 3导入打印函数:

from __future__ import print_function

这允许您使用上面的Python3解决方案。

但是,请注意,flush关键字在从Python 2中的__future__导入的打印函数版本中不可用;它只适用于Python 3,更具体地说是3.3及更高版本。在早期版本中,您仍然需要通过调用sys.stdout.flush()来手动刷新。您还需要在执行此导入的文件中重写所有其他打印语句。

或者可以使用sys.stdout.write()

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

您可能还需要致电

sys.stdout.flush()

以确保立即刷新stdout。

在Python 3+中,print是一个函数。当你打电话时

print('Hello, World!')

Python将其翻译为

print('Hello, World!', end='\n')

你可以随心所欲。

print('Hello, World!', end='')
print('Hello, World!', end=' ')

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

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

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

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

您可以定义如下函数

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

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