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

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

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


当前回答

只需使用end=“”或sep=“”

>>> for i in range(10):
        print('.', end = "")

输出:

.........

其他回答

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

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

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

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

对于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
>>>

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

print('Hello, World!')

Python将其翻译为

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

你可以随心所欲。

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

通常,有两种方法可以做到这一点:

在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),

您可以访问此链接。