Reversing a string
Duncan Booth
duncan.booth at invalid.invalid
Sun Jul 1 05:11:40 EDT 2007
Martin Durkin <nospam at williamsdurkin.co.uk> wrote:
>>>>> def rev(x):
>> mylist = []
>> for char in x:
>> mylist.append(char)
>> mylist.reverse()
>> for letter in mylist:
>> print letter
>>
>> However, compare the incredible difference in clarity and elegance
>> between that and:
>>
>>> >>> 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.
Slicing is one of Pythons great features, but even experienced programmers
often forget that you can have a third argument to a slice or that it can
even be negative.
The syntax for joining a sequence of strings with a separator is ugly, I
sometimes prefer to write it out as:
print str.join('\n', whatever)
or:
joinlines = '\n'.join
...
print joinlines(whatever)
but in this case I'd be as likely to go for an explicit loop for the print:
def rev(x):
for letter in x[::-1]:
print letter
which I think hits about the optimum between brevity and clarity. Your own
optimum point may of course vary.
More information about the Python-list
mailing list