format string to certain line width
fredrik at pythonware.com
Wed Aug 13 14:40:01 CEST 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:
[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.
More information about the Python-list