问题就在标题中。
我想在[tag:Python]中做这件事。我想在这个例子中用[tag:C]做什么。
在C中。
#include <stdio.h>
int main() {
int i;
for (i=0; i<10; i++) printf(".");
return 0;
}
输出。
..........
在Python中。
>>> for i in xrange(0,10): print '.'
.
.
.
.
.
.
.
.
.
.
>>> for i in xrange(0,10): print '.',
. . . . . . . . . .
在Python中print
会增加一个n
或空格,我怎样才能避免这种情况?现在,这只是一个例子。不要告诉我可以先建立一个字符串然后再打印。我想知道如何向stdout
追加`quot;字符串。
import sys
sys.stdout.write('.')
你可能还需要打电话给
sys.stdout.flush()
以确保 "stdout "被立即刷新。
从Python 2.6开始,你可以从Python 3导入print
函数。
from __future__ import print_function
这允许你使用下面的Python 3解决方案。
在Python 3中,print
语句被改成了一个函数。在Python 3中,你可以这样做。
print('.', end='')
这在Python 2中也适用,前提是你已经使用了from __future__ import print_function
。
如果你在缓冲方面有问题,你可以通过添加flush=True
关键字参数来冲洗输出。
print('.', end='', flush=True)
然而,请注意,在Python 2中从__future__
导入的print
函数版本中,flush
关键字是不可用的;它只在Python 3中起作用,更确切地说,是3.3及以后的版本。在早期版本中,你仍然需要通过调用sys.stdout.flush()
来手动刷新。
_注意:这个问题的标题曾经是类似于"如何在python中打印f?"_的内容。
因为人们可能会根据标题来这里寻找,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
..........
新的(从Python 3.0开始)print
函数有一个可选的end
参数,可以让你修改结束符。还有sep
用于分离器。