Reversing a string

Diez B. Roggisch deets at nospam.web.de
Wed Jun 27 19:08:18 CEST 2007


Scott 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.
> 
> 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:
> 
> [code]
>>>>mylist = []
>>>>def rev(x):
>             for char in x:
>                 mylist.append(char)
>                 mylist.reverse()
>                 print mylist
> [/code]

<snip/>

The reverse() is totally useless to apply each when appending each
character. Not only useless, but faulty: if you have a even number of
characters, your string won't be reversed.

All you need to do is this:

>>> x = "abcdefg"
>>> print "".join(reversed(x))
gfedcba


HTH Diez



More information about the Python-list mailing list