考虑在Python中使用print的以下示例:
>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
在每个值之间添加换行符或空格。我怎样才能避免这种情况,从而使输出。。。。相反换句话说,如何将字符串“附加”到标准输出流?
考虑在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')
如何在同一行打印:
import sys
for i in xrange(0,10):
sys.stdout.write(".")
sys.stdout.flush()
通常,有两种方法可以做到这一点:
在Python3.x中无换行打印
在print语句后不追加任何内容,并使用end=“”删除“\n”,如下所示:
>>> print('hello')
hello # Appending '\n' automatically
>>> print('world')
world # With previous '\n' world comes down
# The solution is:
>>> print('hello', end='');print(' world'); # End with anything like end='-' or end=" ", but not '\n'
hello world # It seems to be the correct output
循环中的另一个示例:
for i in range(1,10):
print(i, end='.')
在Python2.x中无换行打印
添加尾随逗号表示:打印后,忽略\n。
>>> print "hello",; print" world"
hello world
循环中的另一个示例:
for i in range(1,10):
print "{} .".format(i),
您可以访问此链接。
你想在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
对于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
>>>