考虑在Python中使用print的以下示例:
>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
在每个值之间添加换行符或空格。我怎样才能避免这种情况,从而使输出。。。。相反换句话说,如何将字符串“附加”到标准输出流?
考虑在Python中使用print的以下示例:
>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
在每个值之间添加换行符或空格。我怎样才能避免这种情况,从而使输出。。。。相反换句话说,如何将字符串“附加”到标准输出流?
当前回答
您不需要导入任何库。只需使用删除字符:
BS = u'\0008' # The Unicode point for the "delete" character
for i in range(10):print(BS + "."),
这将删除换行符和空格(^_^)*。
其他回答
其中许多答案似乎有点复杂。在Python 3.x中,您只需执行以下操作:
print(<expr>, <expr>, ..., <expr>, end=" ")
end的默认值为“\n”。我们只是将其更改为空格,或者您也可以使用end=“”(无空格)来执行printf通常所做的操作。
你想在for循环中打印一些东西;但你不希望每次都用新的行打印。。。
例如:
for i in range (0,5):
print "hi"
OUTPUT:
hi
hi
hi
hi
hi
但你希望它像这样打印:嗨嗨嗨嗨对吗????
只需在打印“hi”后添加逗号。
例子:
for i in range (0,5):
print "hi",
输出:
hi hi hi hi hi
你会注意到以上所有答案都是正确的。但我想做一个捷径,始终在结尾处写入“end=''”参数。
您可以定义如下函数
def Print(*args, sep='', end='', file=None, flush=False):
print(*args, sep=sep, end=end, file=file, flush=flush)
它将接受所有数量的参数。甚至它也会接受所有其他参数,如file、flush等,并使用相同的名称。
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=''
for i in range(5):
print('a',end='')
# aaaaa