[英]How to print over the previous line in python if the previous printed value is the same as the new one?
[英]python: join print with previous printed line
在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
import sys
sys.stdout.write("hello world")
print将应用程序标准写入并添加换行符。
但是,您sys.stdout已经是指向相同位置的文件对象,并且文件对象的write()函数不会自动在输出字符串后添加换行符,因此它应该正是您想要的。
以下应该工作:
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()
的可维护性。
您正在询问打印语句是否可以从上一行的末尾删除换行符。 答案是不。
但是你可以这样写:
if count[0] == '0':
removed = ' ==> %s removed' % (fc)
else:
removed = ''
print '%s records in %s%s' % ('{0:>9}'.format(count), fc, removed)
尽管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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.