[Tutor] Converting a list to a string
Pedro Diaz Jimenez
pdiaz88@terra.es
Mon, 7 May 2001 18:18:08 +0000
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On Monday 07 May 2001 11:15, Michael P. Reilly wrote:
> Praveen Pathiyil wrote
>
> > Hi all,
> >
> > If i have a list=20
> > status =3D ['tftp>', 'Sent', '1943', 'bytes', 'in', '0.0', 'seconds'],
> > is there a single command which will give me a string=20
> > tftp> Sent 1943 bytes in 0.0 seconds
> >
> > OR do i have to do=20
> >
> > stat_str =3D ''
> > for elt in status:
> > stat_str =3D stat_str + ' ' + elt
>
> You don't _have_ to do that; in fact, concatenating strings that way is
> very inefficient (the left hand of the '+' is copied each time through the
> loop). There is a join function/method for strings to do this for you.
>
> In Python 2.0 and higher, you can use string methods, but on the joiner
> (in this case the space):
> stat_str = ' '.join(status)
>
> In earlier releases, use the join function in the string module:
> import string
> stat_str = string.join(status)
>
> Also, if you use the loop above, you'll have an extra space in the
> front of the resulting string. You won't get that with the join
> routines.
>
> -Arcege
Python 1.5.2 (#0, Dec 27 2000, 13:59:38) [GCC 2.95.2 20000220 (Debian
GNU/Linux)] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> A=['a','b','c','d','e']
>>> reduce( lambda x,y:x+y, A )
'abcde'
>>> reduce( lambda x,y:x+" "+y,A
... )
'a b c d e'
>>>
Just my 0.02
Cheers
Pedro
- --
/*
* Pedro Diaz Jimenez
* pdiaz88@terra.es
* pdiaz@acm.asoc.fi.upm.es
*
* Wanna see how 100000! looks like?:
* http://acm.asoc.fi.upm.es/~pdiaz/fact_100.000
*
* La sabiduria me persigue, pero yo soy mas rapido
*/
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.4 (GNU/Linux)
Comment: For info see http://www.gnupg.org
iD8DBQE69ubhnu53feEYxlERAswoAKDYUvpGFAUcBr/bOdpiw+YO2/K6xgCeKYaH
BatcOi4FoBG1LWai9BRh7bs=
=zt1L
-----END PGP SIGNATURE-----