如何打印没有换行或空格的文件?

问题就在标题中。

我想在[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 2.6开始,你可以从Python 3导入print函数。

from __future__ import print_function

这允许你使用下面的Python 3解决方案。

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()来手动刷新。

资料来源

  1. https://docs.python.org/2/library/functions.html#print
  2. https://docs.python.org/2/library/\__future__.html
  3. https://docs.python.org/3/library/functions.html#print
评论(5)

_注意:这个问题的标题曾经是类似于"如何在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
..........
评论(7)

新的(从Python 3.0开始)print函数有一个可选的end参数,可以让你修改结束符。还有sep用于分离器。

评论(1)