To re or not to re ... ( word wrap function?)

Steffen Ries steffen.ries at sympatico.ca
Sat Sep 22 10:59:02 EDT 2001


Skip Montanaro <skip at pobox.com> writes:

> I've been using this to format text for a long time.  It runs on a 1.5.2
> system so it doesn't use string methods or any 2.0+ syntax.
> 
>     def wrap(s, col=74, startcol=0, hangindent=0):
>         """Insert newlines into 's' so it doesn't extend past 'col'.
> 
>         All lines are indented to 'startcol'.  The indentation of the first 
>         line is adjusted further by hangindent.
>         """
>         import re, string
>         s = re.split(r'\s+', s)
>         new_s = [' '*(startcol+hangindent)]
>         append = new_s.append
>         line_len = (startcol+hangindent)
>         for e in s:
>             if not e:
>                 continue
>             if line_len + 1 + len(e) > col:
>                 append('\n'+' '*(startcol)+e)
>                 line_len = len(e) + startcol
                  hangindent=0
                  ^^^^^^^^^^^^
>             else:
>                 if line_len > startcol+hangindent:
>                     append(' ')
>                     line_len = line_len + 1
>                 append(e)
>                 line_len = line_len + len(e)
>         return string.join(new_s, '')

I guess you not using hangindent>0, cause otherwise you would have
noticed a bug... (see above)

/steffen
-- 
steffen.ries at sympatico.ca	<> Gravity is a myth -- the Earth sucks!



More information about the Python-list mailing list