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

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

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


当前回答

您不需要导入任何库。只需使用删除字符:

BS = u'\0008' # The Unicode point for the "delete" character
for i in range(10):print(BS + "."),

这将删除换行符和空格(^_^)*。

其他回答

您可以尝试:

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

您不需要导入任何库。只需使用删除字符:

BS = u'\0008' # The Unicode point for the "delete" character
for i in range(10):print(BS + "."),

这将删除换行符和空格(^_^)*。

蟒蛇3:

print('Hello',end='')

例子:

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

输出:你好,世界

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

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

输出:你好,世界

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

您可以定义如下函数

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

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

使用functools.partal创建名为printf的新函数:

>>> import functools

>>> printf = functools.partial(print, end="")

>>> printf("Hello world\n")
Hello world

用默认参数包装函数是一种简单的方法。