Newbie question: how to join a list of elements of user-defined types?
Michael George Lerner
mlerner at NOSPAM.PLEASE.umich.edu
Mon Apr 29 22:35:16 EDT 2002
Are you sure you're putting appropriate things into the list?
PythonWin 2.2 (#28, Mar 28 2002, 12:10:20) [MSC 32 bit (Intel)] on win32.
Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information.
>>> class MyList(list):
... pass
...
>>> m = MyList()
>>> m.append(1)
>>> m.append(2)
>>> m
[1, 2]
>>> 'apple'.join(m)
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: sequence item 0: expected string, int found
>>> m2 = MyList()
>>> m2.append('one')
>>> m2.append('two')
>>> m2
['one', 'two']
>>> 'apple'.join(m2)
'oneappletwo'
>>> 'flonk'.join([1,2])
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: sequence item 0: expected string, int found
>>>
Fortepianissimo <fortepianissimo at yahoo.com.tw> wrote:
> This question is so fundamental that I strongly suspect it's already
> answered - ig that's the case, please forgive this poor newbie, for he
> has done some work searching over Python FAQ and Google.
> 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.
> Ben
More information about the Python-list
mailing list