Reversing a string

Neil Cerutti horpner at
Wed Jun 27 20:31:01 CEST 2007

On 2007-06-27, Scott <s_broscious at> wrote:
> Yeah I know strings == immutable, but question 1 in section
> 7.14 of "How to think like a computer Scientist" has me trying
> to reverse one.

No, it just wants to to print the characters in reverse, one per

> I've come up with two things, one works almost like it should
> except that every traversal thru the string I've gotten it to
> repeat the "list" again. This is what it looks like:
>>>>mylist = []

That's bad. If you need to use a list in the rev function, you
should bind a new list to a local variable inside rev.

>>>>def rev(x):
>             for char in x:
>                 mylist.append(char)
>                 mylist.reverse()
>                 print mylist

Here's an debugging exercise that you should try.

Please explain what you think each line in the above is supposed
to do. Pretend you are trying to convince me that the above
program works correctly. I bet you will see find your errors
right away as a result of this exercise.

> [/code]

> So I figured maybe make it a generator (I'm not TO familiar
> with generators yet so don't laugh) which changed my code just
> a slight bit:

Experimentation with stuff you don't fully understand is a great
way to learn, but not that useful for solving exercises. ;)

Neil Cerutti
This team is one execution away from being a very good basketball team. --Doc

More information about the Python-list mailing list