Reversing a string

Scott s_broscious at comcast.net
Wed Jun 27 18:53:36 CEST 2007


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]

And the output that sorta works like it should, but threw a curveball, at me 
looks like this:
>>> rev("this is just a test")
['t']
['h', 't']
['i', 't', 'h']
['s', 'h', 't', 'i']
[' ', 'i', 't', 'h', 's']
['i', 's', 'h', 't', 'i', ' ']
['s', ' ', 'i', 't', 'h', 's', 'i']
[' ', 'i', 's', 'h', 't', 'i', ' ', 's']
['j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ']
['u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j']
['s', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u']
['t', 'u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j', 's']
[' ', 's', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u', 't']
['a', 't', 'u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j', 's', ' ']
[' ', ' ', 's', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u', 't', 'a']
['t', 'a', 't', 'u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j', 's', ' ', 
' ']
['e', ' ', ' ', 's', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u', 't', 
'a', 't']
['s', 't', 'a', 't', 'u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j', 's', 
' ', ' ', 'e']
['t', 'e', ' ', ' ', 's', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u', 
't', 'a', 't', 's']


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:

[code]
>>>mylist = []
>>>def rev(x):
            for char in x:
                mylist.append(char)
                mylist.reverse()
                yield mylist
[/code]

But even that threw me a curveball:
>>> rev("this is just a test")
<generator object at 0x00D52170>

So how on earth would be the best way to: Write a function that takes a 
string as an argument and outputs the letters backward, one per line.

It should look like the first char of every list in the top "working" code.

Any help woould be greatly apreciated, and a little bit of explaination as 
to why you did it the way you did would be more helpful than just the code.

Thanks in advance 





More information about the Python-list mailing list