To re or not to re ... ( word wrap function?)
skip at pobox.com
Sat Sep 22 01:40:21 CEST 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:
if line_len + 1 + len(e) > col:
line_len = len(e) + startcol
if line_len > startcol+hangindent:
line_len = line_len + 1
line_len = line_len + len(e)
return string.join(new_s, '')
Skip Montanaro (skip at pobox.com)
More information about the Python-list