Split string at natural break

When rendering the header (using reportlab), I would like to split it between two lines if it is longer than 45 characters. So far I have this:

if len(Title) < 45: drawString(200, 695, Title) else: drawString(200, 705, Title[:45]) drawString(200, 685, Title[45:]) 

The problem is that I want to split the title in a natural break, for example where a space occurs. How can i do this?

+4
source share
4 answers

See this sample code:

 import textwrap print("\n".join(textwrap.wrap("This is my sooo long title", 10))) 

Output:

 This is my sooo long title 

See the full Python document: http://docs.python.org/library/textwrap.html#module-textwrap

+11
source

Use rfind(' ', 0, 45) to find the last space before the border and a break at that position. If there is no space (rfind returns -1), use the code you have.

+1
source
 s = 'this is a long line with a bunch of text for sure and goes on and on ..' brk = s.find(' ', 45) if brk == -1: print s else: print('{:s}\n{:s}'.format(s[:brk], s[brk+1:])) 

Roll up your own and maybe not that elegant .. gives:

 this is a long line with a bunch of text for sure and goes on and on .. 
0
source

Not sure about alternatives. I could suggest, draw a text box with the color of the back ground as the background page with width = 45 and ShrinkToFit = 1. Thus, text over 45 will be compressed at the end of the words ..

0
source

All Articles