python:使用以前的打印行连接打印

时间:2011-03-16 18:49:59

标签: python

在python(2.6)中,是否可以将打印输出与前一行打印输出“连接”?尾随逗号语法(print x,)不起作用,因为大多数输出​​应该有一个新行。

for fc in fcs:
    count = getCount(fc)
    print '%s records in %s' % ('{0:>9}'.format(count),fc)
    if count[0] == '0':
        delete(fc)
        print '==> %s removed' % (fc)

当前控制台输出:

     3875 records in Aaa
     3875 records in Bbb
        0 records in Ccc
==> Ccc removed
    68675 records in Ddd

期望的结果:

     3875 records in Aaa
     3875 records in Bbb
        0 records in Ccc ==> Ccc removed
    68675 records in Ddd

4 个答案:

答案 0 :(得分:3)

import sys
sys.stdout.write("hello world")

打印写入应用程序标准并添加换行符。

但是,sys.stdout已经是指向同一位置的文件对象,并且文件对象的write()函数不会自动将换行符附加到输出字符串,因此它应该正是您想要的。

答案 1 :(得分:2)

以下内容应该有效:

for fc in fcs:
    count = getCount(fc)
    print '%s records in %s' % ('{0:>9}'.format(count),fc),
    if count[0] == '0':
        delete(fc)
        print '==> %s removed' % (fc)
    else:
        print ''

没有一种很好的方法可以缩短其中delete()的可维护性。

答案 2 :(得分:2)

您正在询问print语句是否可以从上一行的末尾删除换行符。答案是否定的。

但你可以写:

if count[0] == '0':
    removed = ' ==> %s removed' % (fc)
else:
    removed = ''
print '%s records in %s%s' % ('{0:>9}'.format(count), fc, removed)

答案 3 :(得分:1)

虽然Python 2没有你想要的功能,但Python 3有。

所以你可以做到

from __future__ import print_function

special_ending = '==> %s removed\n' % (fc)
ending = special_ending if special_case else "\n"

print('%s records in %s' % ('{0:>9}'.format(count),fc), end=ending)
相关问题