[Tutor] Two More Questions

Steven Burr sburr@home.com
Fri, 2 Mar 2001 23:20:28 -0700


On Wednesday, February 28, 2001, at 10:35 PM, Danny Yoo wrote:

> On Wed, 28 Feb 2001 alan.gauld@bt.com wrote:=20
> =20
> > > >>> string.center('''hello world.=20
> > > ... this is a test.''', 45)=20
> > > '         hello world.\012this is a test.        '=20
> > > ###=20
> > > =20
> > > Hmmm... but it depends on the function if it handles a =20
> > > multi-line string properly or not.  string.center() =20
> > > certainly didn't handle that nicely.  =20
> =20
> > Now whether thats what you expected centre to do so is another =20
> > matter, it certainly won't centre each line, but it doesn't =20
> > claim to do so.=20
> =20
> =20
> Very true!  But I still would like it to do something different.  =
*grin*=20
> =20
> Let me see if I can "fix" it:=20
> =20
> ###=20
> >>> def mycenter(multiline, colwidth):=20
> ...     lines =3D string.split(multiline, '\n')=20
> ...     newlines =3D [string.center(l, colwidth) for l in lines]=20
> ...     return string.join(newlines, '\n')=20
> ...=20

You could also use string methods instead of string module functions to =
make a one-line version that is  concise but still readable:

>>> def mycenter(multiline, colwidth):
...          return '\n'.join([line.center(colwidth) for line in =
multiline.split('\n')])=