考虑在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 + "."),

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

其他回答

Python 3.x中的print函数有一个可选的结束参数,可用于修改结束字符:

print("HELLO", end="")
print("HELLO")

输出:

你好,你好

分隔符也有sep:

print("HELLO", "HELLO", "HELLO", sep="")

输出:

你好你好

如果您想在Python2.x中使用它,只需在文件开头添加:

from __future__ import print_function
 for i in range(0, 5): #setting the value of (i) in the range 0 to 5 
     print(i)

上述代码给出以下输出:

 0    
 1
 2
 3
 4

但是,如果您想在一条直线上打印所有这些输出,那么您需要做的就是添加一个名为end()的属性来打印。

 for i in range(0, 5): #setting the value of (i) in the range 0 to 5 
     print(i, end=" ")

输出:

 0 1 2 3 4

不仅是空格,还可以为输出添加其他结尾。例如

 for i in range(0, 5): #setting the value of (i) in the range 0 to 5 
     print(i, end=", ")

输出:

 0, 1, 2, 3, 4, 

记得:

 Note: The [for variable in range(int_1, int_2):] always prints till the variable is 1

 less than it's limit. (1 less than int_2)

或具有如下功能:

def Print(s):
    return sys.stdout.write(str(s))

现在:

for i in range(10): # Or `xrange` for the Python 2 version
    Print(i)

输出:

0123456789

在Python2.x中,您可以在print函数的末尾添加,这样它就不会在新行上打印了。

如何在同一行打印:

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