A suggestion for a possible Python module

Alex Martelli aleax at aleax.it
Tue Mar 4 05:08:36 EST 2003


Max M wrote:
   ...
>      def reverse(aString):
> "Reverse the ordering of letters in a string"
>          list_of_letters = list(aString)
>          list_of_letters.reverse()
>          return ''.join(list_of_letters)
> 
> It would have all the comments you need, and properly, descriptive named
> variables.

As we are being pedantic, I would suggest two more things:

1. a clearer docstring,
2. no mixing of tabs with spaces (the docstring is aligned with a
   tab while the other lines are aligned with spaces).

Point [1] is of course debatable, but, to me, the phrase "in a string"
suggests in-place operation.  Now, of course, this is impossible in
Python, so a savvy reader or user will know what you mean.  However,
it's only a small extra effort to SAY exactly what you mean, e.g.
"Returns a string with the same characters as the argument string,
in reverse order".

[start of rambling aside...]

Using "characters" rather than "letters" is also advisable in the
variable name, but even more important in the docstrings -- not all
characters are letters.  From a function that is specified as
reversing LETTERS, I might expect reverse('23skip45') to return
'23piks45' -- reverse the letters, but leave other characters (that
are not letters) in the same order as in the argument, e.g.:

import re
letters = re.compile('([a-zA-Z]+)')
def revlets(s):
    pieces = letters.split(s)
    def revalpha(s):
        if s.isalpha():
            l = list(s)
            l.reverse()
            return ''.join(l)
        else:
            return s
    return ''.join([revalpha(piece) for piece in pieces])

actually it's not entirely clear whether the task this revlets
function performs is what's desired (e.g., revlets('23skip42foo')
is '23piks42oof' -- is that right, or should it rather return
'23oofp42iks', or...?) -- indicating the specs should be made
a bit more precise in the hypothesis that "reversing letters"
were to be taken literally.  Reversing that "sparse substring"
that IS made of letters while leaving non-letters alone is
quite a different task from what revlets does (it reverses
each compact substring which IS made of letters, independently),
and could be accomplished e.g. by:

def revlets1(s):
    chars = list(s)
    lets = [c for c in chars if c.isalpha()]
    for i in range(len(chars)):
        if chars[i].isalpha():
            chars[i] = lets.pop()
    return ''.join(chars)


Alex





More information about the Python-list mailing list