考虑在Python中使用print的以下示例:
>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
在每个值之间添加换行符或空格。我怎样才能避免这种情况,从而使输出。。。。相反换句话说,如何将字符串“附加”到标准输出流?
考虑在Python中使用print的以下示例:
>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
在每个值之间添加换行符或空格。我怎样才能避免这种情况,从而使输出。。。。相反换句话说,如何将字符串“附加”到标准输出流?
当前回答
在Python 3+中,print是一个函数。当你打电话时
print('Hello, World!')
Python将其翻译为
print('Hello, World!', end='\n')
你可以随心所欲。
print('Hello, World!', end='')
print('Hello, World!', end=' ')
其他回答
for i in xrange(0,10): print '\b.',
这在2.7.8和2.5.2(分别为焓盖和OS X终端)中都有效——不需要模块导入或时间旅行。
您可以在Python 3中执行以下操作:
#!usr/bin/python
i = 0
while i<10 :
print('.', end='')
i = i+1
并使用python filename.py或python3 filename.py。
您可以尝试:
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 + "."),
这将删除换行符和空格(^_^)*。
在Python2.x中,您可以在print函数的末尾添加,这样它就不会在新行上打印了。