How to concatenate list members
Roman Suzi
rnd at onego.ru
Thu May 30 08:26:18 EDT 2002
On Thu, 30 May 2002, Eric Brunel wrote:
What is wrong with:
sep.join(alist)
?
(or, for older Pythons:
import string
string.join(alist, sep)
> Ruediger Maehl wrote:
> > I would like to concatenate all members of a list of strings.
> > How can I do that?
> > I know, I can use a for loop over all elements and concatenate
> > them to one string. But is there another more efficient solution?
> > # ===========================================
> > def concat1(alist, sep=" "):
> > res = ""
> > for e in alist:
> > res += str(e)
> > res += sep
> >
> > return res[:-1]
> >
> > a = ["200100002", "200100003", "200100004"] # many many more to come ...
> >
> > b = concat1(a, "_")
> >
> > print b
> >
> > # and b then looks like this:
> > # "200100002_200100003_200100004"
>
> Try this:
>
> def concat1(alist, sep=" "):
> if not alist: return ''
> return reduce(lambda x,y,sep=sep: x + sep + y, alist)
>
> The "if" is necessary because as it's written, the reduce won't work on
> empty lists.
>
> If you like one-liners, you can also do this:
>
> b = (a and reduce(lambda x,y: x + "_" + y, a)) or ''
>
> HTH
>
Sincerely yours, Roman A.Suzi
--
- Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru -
More information about the Python-list
mailing list