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

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

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


当前回答

为Python 2.6+使用Python 3样式打印函数(它还将打破同一文件中任何现有的带关键字的打印语句)。

# For Python 2 to use the print() function, removing the print keyword
from __future__ import print_function
for x in xrange(10):
    print('.', end='')

为了不破坏所有Python 2打印关键字,请创建一个单独的printf.py文件:

# printf.py

from __future__ import print_function

def printf(str, *args):
    print(str % args, end='')

然后,在文件中使用它:

from printf import printf
for x in xrange(10):
    printf('.')
print 'done'
#..........done

显示printf样式的更多示例:

printf('hello %s', 'world')
printf('%i %f', 10, 3.14)
#hello world10 3.140000

其他回答

 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)

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

print('Hello, World!')

Python将其翻译为

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

你可以随心所欲。

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

只需使用end=''

for i in range(5):
  print('a',end='')

# aaaaa

我最近也有同样的问题。。。

我通过以下方式解决了这个问题:

import sys, os

# Reopen standard output with "newline=None".
# in this mode,
# Input:  accepts any newline character, outputs as '\n'
# Output: '\n' converts to os.linesep

sys.stdout = os.fdopen(sys.stdout.fileno(), "w", newline=None)

for i in range(1,10):
    print(i)

这在Unix和Windows上都有效,但我还没有在Mac OS X上测试过。

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

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

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