[Tutor] Converting a list to a string

Gregor Lingl glingl@aon.at
Mon, 07 May 2001 23:34:44 +0200


Daniel Yoo schrieb:

> On Mon, 7 May 2001, Praveen Pathiyil wrote:
>
> > If i have a list
> > status = ['tftp>', 'Sent', '1943', 'bytes', 'in', '0.0', 'seconds'],
> > is there a single command which will give me a string
> > tftp> Sent 1943 bytes in 0.0 seconds
> >
> > OR do i have to do
> >
> > stat_str = ''
> > for elt in status:
> >     stat_str = stat_str + ' ' + elt
>
> People have suggested using string.join(), which is how I'd approach this
> problem.
>
> However, if you already know how many elements are in your status list,
> you can also use string interpolation toward the cause.
>
>     stat_str = "%s %s %s %s %s %s %s %s" % tuple(status)
>
> would work, assuming that status is an 8-element list.

... or if you don't know the lenght of the list, you may use:

      stat_str = len(status) * "%s " % tuple(status)

which however is definitly neither nicer nor more compact than

      stat_str = " ".join(status)

which is possible since (Python 1.6)

Gregor L.