考虑在Python中使用print的以下示例:
>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
在每个值之间添加换行符或空格。我怎样才能避免这种情况,从而使输出。。。。相反换句话说,如何将字符串“附加”到标准输出流?
考虑在Python中使用print的以下示例:
>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
在每个值之间添加换行符或空格。我怎样才能避免这种情况,从而使输出。。。。相反换句话说,如何将字符串“附加”到标准输出流?
当前回答
在Python2.x中,您可以在print函数的末尾添加,这样它就不会在新行上打印了。
其他回答
您不需要导入任何库。只需使用删除字符:
BS = u'\0008' # The Unicode point for the "delete" character
for i in range(10):print(BS + "."),
这将删除换行符和空格(^_^)*。
蟒蛇3:
print('Hello',end='')
例子:
print('Hello',end=' ')
print('world')
输出:你好,世界
此方法在提供的文本之间添加sperator:
print('Hello','world',sep=',')
输出:你好,世界
如何在同一行打印:
import sys
for i in xrange(0,10):
sys.stdout.write(".")
sys.stdout.flush()
使用functools.partal创建名为printf的新函数:
>>> import functools
>>> printf = functools.partial(print, end="")
>>> printf("Hello world\n")
Hello world
用默认参数包装函数是一种简单的方法。
Python 3:
print('.', end='')
Python 2.6+:
from __future__ import print_function # needs to be first statement in file
print('.', end='')
Python<=2.5:
import sys
sys.stdout.write('.')
如果每次打印后都有多余的空间,在Python 2中:
print '.',
Python 2中的误导-避免:
print('.'), # Avoid this if you want to remain sane
# This makes it look like print is a function, but it is not.
# This is the `,` creating a tuple and the parentheses enclose an expression.
# To see the problem, try:
print('.', 'x'), # This will print `('.', 'x') `