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

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

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


当前回答

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

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

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上测试过。

其他回答

只需使用end=''

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

# aaaaa

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

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

您可以访问此链接。

在Python 3中,可以使用print函数的sep=和end=参数:

要不在字符串末尾添加换行符,请执行以下操作:

print('.', end='')

要在要打印的所有函数参数之间不添加空格,请执行以下操作:

print('a', 'b', 'c', sep='')

您可以将任何字符串传递给任一参数,并且可以同时使用两个参数。

如果缓冲有问题,可以通过添加flush=True关键字参数来刷新输出:

print('.', end='', flush=True)

Python 2.6和2.7

从Python 2.6中,您可以使用__future__模块从Python 3导入打印函数:

from __future__ import print_function

这允许您使用上面的Python3解决方案。

但是,请注意,flush关键字在从Python 2中的__future__导入的打印函数版本中不可用;它只适用于Python 3,更具体地说是3.3及更高版本。在早期版本中,您仍然需要通过调用sys.stdout.flush()来手动刷新。您还需要在执行此导入的文件中重写所有其他打印语句。

或者可以使用sys.stdout.write()

import sys
sys.stdout.write('.')

您可能还需要致电

sys.stdout.flush()

以确保立即刷新stdout。

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

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

输出:

你好,你好

分隔符也有sep:

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

输出:

你好你好

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

from __future__ import print_function

为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