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

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

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


当前回答

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

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

您可以访问此链接。

其他回答

或具有如下功能:

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

现在:

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

输出:

0123456789
for i in xrange(0,10): print '\b.',

这在2.7.8和2.5.2(分别为焓盖和OS X终端)中都有效——不需要模块导入或时间旅行。

使用functools.partal创建名为printf的新函数:

>>> import functools

>>> printf = functools.partial(print, end="")

>>> printf("Hello world\n")
Hello world

用默认参数包装函数是一种简单的方法。

为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

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

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

您可以访问此链接。