Reversing a string
Martin Durkin
nospam at williamsdurkin.co.uk
Mon Jul 2 00:38:17 EDT 2007
aleax at mac.com (Alex Martelli) wrote in
news:1i0kjpx.wjw44j15np22dN%aleax at mac.com:
> 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.
>>
>> 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.
>
sorry you've lost me there.
>
> So, something like:
>
> for c in reversed(x): print c
>
> is mostly likely how I'd present the solution to the task.
This is an interesting point to me. I am just learning Python and I
wonder how I would know that a built in function already exists?
At what point do I stop searching for a ready made solution to a
particular problem and start programming my own function?
Is it just a matter of reading *all* the documentation before I start
coding?
More information about the Python-list
mailing list