format string to certain line width

John Machin sjmachin at lexicon.net
Wed Aug 13 14:48:15 CEST 2008


On Aug 13, 10:13 pm, elukk... at cmbi.ru.nl wrote:
> >>>> import textwrap
> >>>> print textwrap.fill("HelloWorld", 2)
> > He
> > ll
> > oW
> > or
> > ld
>
> > Of course if your assertion that the string contains no spaces, tabs or
> > newlines turns out to be incorrect this may not do what you wanted.
>
> 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?
> The perl syntax i posted is much faster.

>>> def julienne(s, w):
...     return ''.join(s[x:x+w] + '\n' for x in xrange(0, len(s), w))
...
>>> julienne('HelloWorld', 2)
'He\nll\noW\nor\nld\n'
>>> julienne('HelloWorld', 3)
'Hel\nloW\norl\nd\n'
>>> julienne('HelloWorld', 99)
'HelloWorld\n'
>>>



More information about the Python-list mailing list