When using Python's textwrap library, how can I turn this:
short line,
long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
into this:
short line,
long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxx
I tried:
w = textwrap.TextWrapper(width=90,break_long_words=False)
body = '\n'.join(w.wrap(body))
But I get:
short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
(spacing not exact in my examples)
How about wrap only lines longer then 90 characters?
TextWrapper is not designed to handle text that already has newlines in it.
There are a two things you may want to do when your document already has newlines:
1) Keep old newlines, and only wrap lines that are longer than the limit.
You can subclass TextWrapper as follows:
Then use it the same way as textwrap:
Gives you:
2) Remove the old newlines and wrap everything.
Gives you
(TextWrapper doesn't do either of these - it just ignores the existing newlines, which leads to a weirdly formatted result)