考虑在Python中使用print的以下示例:
>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
在每个值之间添加换行符或空格。我怎样才能避免这种情况,从而使输出。。。。相反换句话说,如何将字符串“附加”到标准输出流?
考虑在Python中使用print的以下示例:
>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
在每个值之间添加换行符或空格。我怎样才能避免这种情况,从而使输出。。。。相反换句话说,如何将字符串“附加”到标准输出流?
当前回答
只需使用end=''
for i in range(5):
print('a',end='')
# aaaaa
其他回答
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') `
你会注意到以上所有答案都是正确的。但我想做一个捷径,始终在结尾处写入“end=''”参数。
您可以定义如下函数
def Print(*args, sep='', end='', file=None, flush=False):
print(*args, sep=sep, end=end, file=file, flush=flush)
它将接受所有数量的参数。甚至它也会接受所有其他参数,如file、flush等,并使用相同的名称。
或具有如下功能:
def Print(s):
return sys.stdout.write(str(s))
现在:
for i in range(10): # Or `xrange` for the Python 2 version
Print(i)
输出:
0123456789
如何在同一行打印:
import sys
for i in xrange(0,10):
sys.stdout.write(".")
sys.stdout.flush()
为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