import re import string _stripstart = re.compile('^(\s*[\n\r])+') def wrap(text,width=70): # Strip trailing whitespace and expand tabs for proper counting. text = string.expandtabs(string.rstrip(text)) # Strip all leading blank lines text = _stripstart.sub('',text,1) # Our output out = '' # When I grow up, I want to be a Perl programmer for m in re.findall( '(?mx) [^\n]{1,%d} (?=\s) [ ]* [\n]? | [^\n]{1,%d} [\n]? | \n' % (width,width),text): out = out + string.rstrip(m) + '\n' return string.rstrip(out) if __name__ == '__main__': a = ''' this is a long string that hopefully will be wrapped correctly so lets see how it goes. Note that this line is indented. Blah blah blah blah This line terminates on exactly the sixtyninth character so toto test This line terminates on exactly the seventy-eth character to test This line terminates on exactly the seventyfirst character to test ifit blah two blank lines above 70 chars on the next line 1234567890123456789012345678901234567890123456789012345678901234567890 80 chars on the next line 12345678901234567890123456789012345678901234567890123456789012345678901234567890 160chars on the next line 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 ''' a = wrap(a) print a