考虑在Python中使用print的以下示例:
>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
在每个值之间添加换行符或空格。我怎样才能避免这种情况,从而使输出。。。。相反换句话说,如何将字符串“附加”到标准输出流?
考虑在Python中使用print的以下示例:
>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
在每个值之间添加换行符或空格。我怎样才能避免这种情况,从而使输出。。。。相反换句话说,如何将字符串“附加”到标准输出流?
当前回答
注意:这个问题的标题以前类似于“How to printf in Python”
由于人们可能会根据标题来这里寻找它,Python也支持printf样式替换:
>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
... print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three
而且,您可以方便地相乘字符串值:
>>> print "." * 10
..........
其他回答
for i in xrange(0,10): print '\b.',
这在2.7.8和2.5.2(分别为焓盖和OS X终端)中都有效——不需要模块导入或时间旅行。
如何在同一行打印:
import sys
for i in xrange(0,10):
sys.stdout.write(".")
sys.stdout.flush()
通常,有两种方法可以做到这一点:
在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),
您可以访问此链接。
只需使用end=“”或sep=“”
>>> for i in range(10):
print('.', end = "")
输出:
.........
注意:这个问题的标题以前类似于“How to printf in Python”
由于人们可能会根据标题来这里寻找它,Python也支持printf样式替换:
>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
... print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three
而且,您可以方便地相乘字符串值:
>>> print "." * 10
..........