Python: 使用for循环将字符串拆分为子字符串

3
我有一个像这样的字符串:
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个字符)。

你说的“cutting the spaces”是什么意思? - SilentGhost
3个回答

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可以在单词边界内断行吗?等等,我想这就是提问者想要的,我刚刚重新读了一遍问题。 - intuited

1

我认为最清晰的方式是

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

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

编辑:我重新阅读了你的问题,并意识到我不确定你是否想要在单词边界上换行还是仅在每行的第55个字符处硬换行。

如果您确实想要在单词边界上换行,则应查看由unutbu和SilentGhost提出的建议,并使用textwrap模块。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接