Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: breaking a string into substrings using a for loop

Tags:

python

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)

like image 790
Alex Gordon Avatar asked May 17 '26 04:05

Alex Gordon


1 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
like image 93
unutbu Avatar answered May 19 '26 16:05

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!