2010-10-07 65 views
3

子我有一個字符串是這樣的:蟒蛇:打破字符串轉換成使用for循環

row='saint george 1739 1799 violin concerti g 029 039 050 symphonie concertante for two violins g 024 bertrand cervera in 024 039 christophe guiot in 024 029 and thibault vieux violin soloists orchestre les archets de paris' 

我有這樣的循環:

for n in range (1,int(len(row)/55)+1): 
print row[(n-1)*55:n*55] 

這是工作嘛!!

但是,它正在削減的空間:

saint george 1739 1799 violin concerti g 029 039 050 sy 
mphonie concertante for two violins g 024 bertrand cerv 
era in 024 039 christophe guiot in 024 029 and thibault 

我不希望它切的空間(不過我還是希望無論是55個字符或每行以內)

+0

你是什麼意思「切割空間」? – SilentGhost 2010-10-07 22:57:54

回答

4
import textwrap 

row='saint george 1739 1799 violin concerti g 029 039 050 symphonie concertante for two violins g 024 bertrand cervera in 024 039 christophe guiot in 024 029 and thibault vieux violin soloists orchestre les archets de paris' 

print(textwrap.fill(row,width=55)) 
# saint george 1739 1799 violin concerti g 029 039 050 
# symphonie concertante for two violins g 024 bertrand 
# cervera in 024 039 christophe guiot in 024 029 and 
# thibault vieux violin soloists orchestre les archets de 
# paris 
3

看看textwrap模塊。

+0

'textwrap'可以在單詞邊界內打破嗎?呃,等等,這就是OP想要的,我想......我只是重讀這個問題。 – intuited 2010-10-07 22:59:33

1

我認爲最清楚的方式將是

for i in range(0, len(row), 55): 
    print test[i:i+55] 

哪裏range的第三個參數是step值,即範圍內的元素之間的差異。

編輯:剛剛重讀您的問題,並意識到我不確定您是否希望它突破字邊界或只是在每行的第55個字符處做一個硬性休息。

如果你確實想讓它沿着單詞邊界突破,你應該通過unutbu和SilentGhost檢查textwrap模塊爲suggested

+0

非常感謝。我編輯了一下這個問題 – 2010-10-07 22:57:15