[Tutor] Str Method
Steven D'Aprano
steve at pearwood.info
Fri Nov 2 01:19:18 CET 2012
On 02/11/12 02:34, Ashley Fowler wrote:
> Question is how do you implement the "curly brackets" in my str method?
>
> This is what I have so far...
>
> def __init__( self, *initElements ):
> self._theElements = list()
>
> def __str__(self):
> return self._theElements
__str__ should return a string, not a list. Since _theElements is a list,
you cannot rightly return that. You could convert that to a string first:
s = str(self._theElements)
and then replace the square brackets [ ] with curly brackets:
s = s.replace("[", "{").replace("]", "}")
return s
Another way is to build the string yourself:
s = ', '.join(str(item) for item in self._theElements)
return '{' + s + '}'
--
Steven
More information about the Tutor
mailing list