format string to certain line width

Duncan Booth duncan.booth at invalid.invalid
Wed Aug 13 13:46:08 CEST 2008


elukkien at cmbi.ru.nl wrote:

> I'm trying to find a way to print out a long string (>400 characters
> no spaces, tabs or newlines) to a line width of 60 characters. So
> after every 60 characters a newline would start. Is it possible to
> transform the string to set the linewidth?
> 
> for example for a linewidth of 2:
> 
>>>>str = "HelloWorld!"
> 
> ... {do something to str to set width to 2} ...
> 
>>>>print str
> He
> LL
> oW
> or
> ld
> !

>>> 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.

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list