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

Skip Montanaro skip at pobox.com
Fri Sep 21 19:40:21 EDT 2001


    Chris> I was just asked if it would be hard to write a script that would
    Chris> take the output from an MS word: "save as text" operation, and
    Chris> re-format it so it was wrapped to 80 character lines. 

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
            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, '')

-- 
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list