python:使用for循环将字符串分解为子字符串

时间:2010-10-07 22:50:25

标签: python

我有一个这样的字符串:

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个字符或更少)

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

查看textwrap模块。

答案 2 :(得分:1)

我认为最明确的方式是

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

其中range的第三个参数是step值,即范围元素之间的差异。

编辑:只是重新阅读你的问题,并意识到我不确定你是否希望它突破单词边界或只是在每一行的第55个字符处进行一次艰难的休息。 / p>

如果您确实希望它突破字边界,您应该通过unutbu和SilentGhost将textwrap模块检出为suggested