# A suggestion for a possible Python module

Alex Martelli aleax at aleax.it
Tue Mar 4 09:47:15 CET 2003

```Erik Max Francis wrote:

> Lance LaDamage wrote:
>
>> I have noticed that there is one thing that everyone wishes to do in
>> Python
>> ... reverse a string.
>
> Who's everyone?  I can't remember needing desperately to reverse a
> string once in my entire programming life.

I have used reversing (on all sorts of sequences -- not jsut strings)
to perform in-place "subsequence shifts", a la Gries.  Suppose a
sequence type X has a method x.reverse(from, onto) that in-place
reverses a subsequence of x; then, to go from x == A+B+C+D to
x == A+C+B+D form subsequences A, B, C and D of lengths a, b, c and
d respectively, entirely in-place, you can use:
x.reverse(a, a+b+c)
x.reverse(a, a+c)
x.reverse(a+c, a+c+b)

So, "in-place reverse subsequence" is a powerful primitive for all
kinds of "subsequence shifts".  However, with Python strings being
immutable, such a primitive wouldn't be very useful -- you'd have
to build a new string anyway so you might as well do it in one go,
x = ''.join(( x[:a], x[a+b:a+b+c], x[a:a+b], x[a+b+c:] ))
or the like.

Still, I do think Gries' algorithm would be a good reason to add
optional start and stop arguments to Python lists' *reverse*
method.  Hmmm...

>> As you know, in Visual Basic, the function for
>> performing this operation is indeed StrReverse(s).
>
> It's pretty trivial in Python as it is:
>
>>>> s = 'hello'
>>>> l = list(s)
>>>> l.reverse()
>>>> ''.join(l)
> 'olleh'
>

It's way simpler in Python 2.3, of course, since it finally supports
extended slicing for built-in sequences, including strings:

[alex at lancelot alex]\$ python
Python 2.3a2 (#1, Feb 21 2003, 10:22:48)
[GCC 3.2 (Mandrake Linux 9.0 3.2-1mdk)] on linux2