Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string at a natural break

Tags:

python

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?

like image 340
jdickson Avatar asked Dec 16 '22 23:12

jdickson


2 Answers

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

like image 183
Gilles Quenot Avatar answered Dec 18 '22 12:12

Gilles Quenot


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.

like image 27
Mark Ransom Avatar answered Dec 18 '22 12:12

Mark Ransom