format string to certain line width

elukkien at cmbi.ru.nl elukkien at cmbi.ru.nl
Wed Aug 13 06:19:48 EDT 2008


Hello!

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
!

i know in Perl this works:
my $str = "HelloWorld!"  ;
$str =~ s/.{2}/$&\n/g  ; #at {2} you can then specify the desired width
print $ str  ;

But how to do it in Python?
An option in the print statement would also be fine.
Something like: print "%{2}s" %(str)

Of course i could do it in a for loop and print 60 characters, print a \n,
print the next 60 characters, print a \n ...
But i imagine there will be a more efficient way.

Thanks
Eddie




More information about the Python-list mailing list