invert or reverse a string... warning this is a rant

Tim N. van der Leeuw tnleeuw at gmail.com
Fri Oct 20 11:55:24 EDT 2006


Fredrik Lundh wrote:
> Tim N. van der Leeuw wrote:
>
> > In practice, the short-term fix would be to add a __str__ method to the
> > 'reversed' object
>
> so what should
>
>     str(reversed(range(10)))
>
> do ?
>

My idea was that reversed.__str__() would do something like the
equivalent of ''.join(reversed(...))

Playing in the interactive shell with that idea I quickly realized that
this would of course consume the iterator as a side-effect... Which is
most likely to be undesirable.

(It works well if you just write it as in the examples above, where the
'reversed' object is temporary and instantly thrown away. But if you
assign the iterator object, in this case 'reversed', to an instance
variable then it should be immediately obvious that having the iterator
consumed as side-effect of calling it's __str__ method is very, very
wrong...)


> > and perhaps to all iterators too (so that trying to build a string from an
> > iterator would do the obvious thing).
>
> all iterators?  who's going to do that?
>

It's not as easy as I expected. But if we could come up with a
reasonable way to create a __str__ method for iterators, well who knows
I might give it a go. (It would be my first C code in many years
though)


> </F>

Cheers,

--Tim




More information about the Python-list mailing list