开发者

python: join print with previous printed line

In python (2.6) is it possilbe to "join" print output with the previous line of print output? The trailing comma syntax ( print x,) doesn't work because most of the output should have a new line.

for fc in fcs:
    count = getCount(fc)
    print '%s records in %s' % ('{0:>9}'.format(count),开发者_如何学Cfc)
    if count[0] == '0':
        delete(fc)
        print '==> %s removed' % (fc)

current console output:

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

desired result:

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


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

print writes to the apps standard out and adds a newline.

However you sys.stdout is already a file object pointing to the same location and the write() function of a file object doesn't automatically append a newline to the output string so it should be exactly what you want.


You're asking if a print statement can remove the newline from the end of the previous line. The answer is no.

But you can write:

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


The following should work:

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 ''

There isn't a very good way to shorten that an maintain readability with the delete() in there.


While Python 2 doesn’t have the feature you look for, Python 3 has.

so you can do

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜