简体   繁体   中英

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)

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.

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.

If you do want it to break along word boundaries, you should check out the textwrap module as suggested by unutbu and SilentGhost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM