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

Tim N. van der Leeuw tnleeuw at gmail.com
Fri Oct 20 10:02:50 EDT 2006


I V wrote:
> On Fri, 20 Oct 2006 09:04:07 +1000, Steven D'Aprano wrote:
> > I agree -- the reversed() function appears to be an obvious case of purity
> > overriding practicality :(
> >
> >>>> str(reversed("some string"))
> > '<reversed object at 0xb7edca4c>'
> >>>> repr(reversed("some string"))
> > '<reversed object at 0xb7edca4c>'
>
> This doesn't seem particularly "pure" to me, either. I would
> have thought str(some_iter) should build a string out of the iterator, as
> list(some_iter) or dict(some_iter) do. I guess this might have to wait for
> Python 3, but str ought to be a proper string constructor, not a "produce
> a printable representation of" function, particularly when we have repr to
> do the latter.

The failing of str(reversed('the string')) caught me off-guard too. I
think you're quite right that it would be good if str() becomes a
proper constructor.

In practice, the short-term fix would be to add a __str__ method to the
'reversed' object, and perhaps to all iterators too (so that trying to
build a string from an iterator would do the obvious thing).

Cheers,

--Tim




More information about the Python-list mailing list