[Tutor] Converting a list to a string
Michael P. Reilly
arcege@speakeasy.net
Mon, 7 May 2001 13:58:48 -0400 (EDT)
Daniel Yoo wrote
>
> 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.
Likewise, if you don't know how many:
>>> if status: # there's at least one
... spam_str = '%s' + ' %s' * (len(status)-1)
... stat_str = spam_str % tuple(status)
... else:
... stat_str = ''
...
But I think join is faster than this. ;)
-Arcege
--
+----------------------------------+-----------------------------------+
| Michael P. Reilly | arcege@speakeasy.net |