Python Textwrap - forcing 'hard' breaks

Posted by Tom Werner on Stack Overflow See other posts from Stack Overflow or by Tom Werner
Published on 2010-05-19T12:04:32Z Indexed on 2010/05/19 12:20 UTC
Read the original article Hit count: 184

Filed under:
|
|

I am trying to use textwrap to format an import file that is quite particular in how it is formatted. Basically, it is as follows (line length shortened for simplicity):

abcdef <- Ok line
abcdef 
 ghijk <- Note leading space to indicate wrapped line
 lm

Now, I have got code to work as follows:

wrapper = TextWrapper(width=80, subsequent_indent=' ', break_long_words=True, break_on_hyphens=False)
for l in lines:
  wrapline=wrapper.wrap(l)

This works nearly perfectly, however, the text wrapping code doesn't do a hard break at the 80 character mark, it tries to be smart and break on a space (at approx 20 chars in).

I have got round this by replacing all spaces in the string list with a unique character (#), wrapping them and then removing the character, but surely there must be a cleaner way?

N.B Any possible answers need to work on Python 2.4 - sorry!

© Stack Overflow or respective owner

Related posts about python

Related posts about textwrap