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 个回答
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()
的情况下,想要缩短代码而又保持可读性,其实并没有很好的办法。
3
import sys
sys.stdout.write("hello world")
print这个函数是用来输出内容到应用程序的标准输出,并且会在内容后面加一个换行符。
不过,你的sys.stdout其实已经是一个指向相同位置的文件对象,而文件对象的write()函数在输出字符串时不会自动加上换行符,所以它的行为正好符合你的需求。
2
你在问一个打印语句是否可以去掉前一行末尾的换行符。答案是不能。
不过你可以这样写:
if count[0] == '0':
removed = ' ==> %s removed' % (fc)
else:
removed = ''
print '%s records in %s%s' % ('{0:>9}'.format(count), fc, removed)