views:

306

answers:

4

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)

+3  A: 

try

w = textwrap.TextWrapper(width=90,break_long_words=False,replace_whitespace=False)

that seemed to fix the problem for me

I worked that out from what I read here (I've never used textwrap before)

Peter
+1  A: 

How about wrap only lines longer then 90 characters?

new_body = ""
lines = body.split("\n")

for line in lines:
    if len(line) > 90:
        w = textwrap.TextWrapper(width=90, break_long_words=False)
        line = '\n'.join(w.wrap(line))

    new_body += line + "\n"
zdmytriv
+1  A: 

It looks like it doesn't support that. This code will extend it to do what I need though:

http://code.activestate.com/recipes/358228/

Greg
A: 
lines = text.split("\n")
lists = (textwrap.TextWrapper(width=90,break_long_words=False).wrap(line) for line in lines)
body  = "\n".join("\n".join(list) for list in lists)
John Kugelman