invert or reverse a string... warning this is a rant
paul at boddie.org.uk
Thu Oct 19 20:41:21 CEST 2006
James Stroud wrote:
> It would provide symmetry for reversing any sequence (without requiring
> an iterator).
That might infuriate those who regard strings as "mischievous"
sequences (ie. things which cause errors because you think you have a
list, but you're actually accessing characters in a string), but it's a
valid point: the built-in sequence types should, within reason, provide
a similar interface.
The proposed solution involving slicing syntax does seem odd in the
sense that it's highly similar to the redundant-for-strings s[:]
operation, and it might require inspiration for anyone looking for
convenience methods on the string object to consider using slicing
instead in this manner. In looking for alternative approaches, I became
somewhat distracted by the classic approach you'd use with certain
functional languages: convert the string into a list of characters (if
it isn't already treated as a list), reverse the list, concatenate the
list. The following requires Python 2.4:
I guess Python 2.5 has the reversed method of which you speak. Still,
the simplest things are often the best, and Python's classic operators
(indexing, slicing) should always be kept in mind.
More information about the Python-list