Newbie question: how to join a list of elements of user-defined types?
Fernando Pérez
fperez528 at yahoo.com
Mon Apr 29 22:15:28 EDT 2002
Fortepianissimo wrote:
> Basically I want to have a subclass of list, like
>
> class MyList (list):
> ...
>
> then I want to
>
> l=MyList()
> ... do stuff to fill l
> s=" ".join(l)
>
> with the hope that s will be a nicely joined string with " " as the
> delimiter. Given my C++ background, I tried to define __str__/__repr__
> for both MyList and the user-defined types of the list members,
> assuming the type conversion would silently be invoked. But I was
> wrong!
>
> Even trying this failed:
>
> l=[1,2,3]
> s=" ".join(l)
>
> and I thought built-in types all have default __str__ and __repr__?
>
> What am I missing here? Many thanks to someone who would take time to
> rescue a poor soul.
Well, this quick solution seems to work. It's probably an ugly/inefficient
one, so wait for the gurus for a deep/elegant one ;) But in the meantime
this may get you going:
In [25]: class mystr(str):
....: def join(self,alist):
....: template = ('%s'+self.__str__()) * (len(alist)-1) + '%s'
....: return template % tuple(alist)
....:
In [26]: mystr(' ').join(l)
Out[26]: '1 2 3'
In [27]: l
Out[27]: [1, 2, 3]
cheers,
f
More information about the Python-list
mailing list