2011-03-16 115 views
1

在python(2.6)中,是否可以將打印輸出與前一行打印輸出「加入」?尾隨逗號語法(print x,)不起作用,因爲大部分輸出應該都有新的一行。python:加入前一行打印輸出

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 

回答

2

您在問打印聲明是否可以從上一行的末尾刪除換行符。答案是不。

但你可以這樣寫:

if count[0] == '0': 
    removed = ' ==> %s removed' % (fc) 
else: 
    removed = '' 
print '%s records in %s%s' % ('{0:>9}'.format(count), fc, removed) 
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 '' 

沒有縮短一個很好的方法即與保持可讀性那裏有。

+0

感謝迅速的反應。在代碼示例中,我省略了「delete(fc)'行,所以你的答案不再有效(我認爲?)。 – 2011-03-16 19:00:06

+0

哦,你是絕對正確的,我撇開了這個問題,並專注於它的印刷方面,對不起,我會做一個編輯。 – 2011-03-16 19:02:02

+0

謝謝安德魯。我接受了湯姆的回答,因爲我明白了它是如何工作的。我很欣賞知道另一條路線來達到同樣的目的。 – 2011-03-16 19:44:21

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

打印寫入應用程序標準並增加了一個換行符。

但是,您的sys.stdout已經是指向同一位置的文件對象,並且文件對象的write()函數不會自動將新行添加到輸出字符串,因此它應該完全符合您的需要。

+0

你在'locatino'中翻轉你的'n'和'o'...還是你? – John 2011-08-29 14:06:50

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

謝謝你讓我看看我升級時需要做什麼。 – 2011-03-16 19:45:07

+0

也許不是我寫過的最好的python代碼,但我希望你明白了:) – 2011-03-16 21:23:52