Python: breaking a string into substrings using a for loop

I have a line 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 works well.

however, it cuts 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 don't want it to narrow spaces (however, I still want either 55 characters or fewer lines)

+3
source share
3 answers
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
+4
source

look at the textwrapmodule.

+3
source

,

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

range - step, .. .

edit: , , , 55- .

, , textwrap , unutbu SilentGhost.

+1

Source: https://habr.com/ru/post/1768519/


All Articles