[英]python: breaking a string into substrings using a for loop
i have a string like this: 我有一个像这样的字符串:
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'
i have this loop: 我有这个循环:
for n in range (1,int(len(row)/55)+1):
print row[(n-1)*55:n*55]
it is working well!! 它运作良好!!
however, it is cutting the spaces: 然而,它正在削减空间:
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
i do not want it to cut the spaces (however i still want either 55 characters or less per line) 我不希望它削减空格(但我仍然希望每行55个字符或更少)
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
看看textwrap
模块。
I think the clearest way would be 我认为最清楚的方式是
for i in range(0, len(row), 55):
print test[i:i+55]
where the third parameter to range
is the step
value, ie the difference between range elements. 其中range
的第三个参数是step
值,即范围元素之间的差异。
edit : just reread your question, and realized that I'm not sure if you want it to break along word boundaries or to just do a hard break at the 55th character of each line. 编辑 :只是重读你的问题,并意识到我不确定你是否希望它突破单词边界或只是在每一行的第55个字符处进行一次艰难的休息。
If you do want it to break along word boundaries, you should check out the textwrap
module as suggested by unutbu and SilentGhost. 如果你确实希望它突破单词边界,你应该按照unutbu和textwrap
建议检查textwrap
模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.