>>> import textwrap
>>> help(textwrap.wrap)
wrap(text, width=70, **kwargs)
Wrap a single paragraph of text, returning a list of wrapped lines.
Reformat the single paragraph in 'text' so it fits in lines of no
more than 'width' columns, and return a list of wrapped lines. By
default, tabs in 'text' are expanded with string.expandtabs(), and
all other whitespace characters (including newline) are converted to
space. See TextWrapper class for available keyword args to customize
wrapping behaviour.
>>> s = "a" * 20
>>> s = "\n".join(textwrap.wrap(s, width=10))
>>> print s
aaaaaaaaaa
aaaaaaaaaa
Any extra newlines inserted will be treated as space when the web page is processed by the browser.
Alternatively:
def break_long_words(s, width, fix):
return " ".join(x if len(x) < width else fix(x) for x in s.split())
def handle_long_word(s): # choose a name that describes what action you want
# do something
return s
s = "a" * 20
s = break_long_words(s, 60, handle_long_word)