Reversing a string

Frank Swarbrick infocat at
Mon Jul 2 04:11:47 CEST 2007

Alex Martelli wrote:
> Martin Durkin <nospam at> wrote:
>    ...
>>>>>>>>> print "\n".join("spam"[::-1])
>    ...
>>>> OK, maybe I'm missing the point here as I'm new to Python. The first
>>>> one seems clearer to me. What am I missing?
>>> I think all you are missing is familarity with Python, but I too don't
>>> like one-liners simply for their own sake.
>> I guess that's it. The first one reads more like a textbook example which
>> is about where I am at. Is there any speed benefit from the one liner?
> The first example reads "excruciatingly low-level" to me: its autor is
> thinking in terms of what the machine is doing, mapped into pretty
> elementary low-level constructs.
> The second example depends first of all on knowledge of extended-slicing
> (specifically the fact that x[::-1] is a reversal, because of the
> negative -1 "step" aka "stride").  If you don't know about extended
> slicing, you're unlikely to just "get it from context", because it uses
> a syntax based on punctuation rather than readable words whose meaning
> you might guess at.  Python has a modest amount of such "punctuation
> syntax" -- about the same amount as C but definitely more than Cobol
> (where one would typically write "ADD a TO b" to avoid shocking totally
> clueless readers with "mysterious punctuation" such as "a + b"...!!!-).
> Punctuation is often very concise but not "intrinsically obvious" unless
> you've been exposed to it already;-).

Since you mentioned Cobol I couldn't resist...

move "spam" to spam
Display Function Reverse(spam)

There's also slicing (known in Cobol as "reference modification")
move mystring(5:3) to my-newstring
* moves 3 characters starting with character 5

No "negative" slicing, though it could be simulated with Function 
Reverse() and ref.mod.


More information about the Python-list mailing list