format string to certain line width

Fredrik Lundh fredrik at pythonware.com
Wed Aug 13 08:40:01 EDT 2008


elukkien at cmbi.ru.nl wrote:

> Thanks, i just found this myself and it works fine, but very slow...
> The script without the wrapping takes 30 seconds, with wrapping 30
> minutes. Is there not a more efficient way?

sounds like you're wrapping a few million long strings, not just one...

here are two approaches that are about 10x faster than textwrap:

     re.findall('..', my_string)

or

     [my_string[i:i+2] for i in xrange(0, len(my_string), 2]

the above gives you lists of string fragments; you can either join them 
before printing; e.g.

     print "'\n'.join(re.findall('..', my_string))

or use writelines directly:

     sys.stdout.writelines(s + "\n" for s in re.findall('..', my_string))

Python's re.sub isn't as efficient as Perl's corresponding function, so 
a direct translation of your Perl code to

     re.sub('(..)', r'\1\n', my_string)

or, faster (!):

     re.sub('(..)', lambda m: m.group() + "\n", my_string)

is not as fast as the above solutions.

</F>




More information about the Python-list mailing list