4

While rendering a title (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 with this is that I only want to split the title at a natural break, such as where a space occurs. How do I go about accomplishing this?

jdickson
  • 696
  • 1
  • 9
  • 21

4 Answers4

11

See this sample code :

import textwrap

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

The output :

This is my
sooo long
title

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

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
1

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

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
0
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 your own and perhaps not that elegant .. yields:

this is a long line with a bunch of text for sure
and goes on and on ..
Levon
  • 138,105
  • 33
  • 200
  • 191
0

Am not sure about alternatives. I could suggest, draw the text box with back ground color as background page with width= 45 and ShrinkToFit=1. So text more than 45 will be shrinked at end of words..

Sathish K
  • 1
  • 2