[Tutor] Working with strings
Michael P. Reilly
arcege@shore.net
Mon, 12 Mar 2001 11:42:40 -0500 (EST)
[Charset iso-8859-1 unsupported, filtering to ASCII...]
> Hi- I'm going through the OBP tutorial on how to think like a scientist by Allen B. Downey and Jeffrey Elkner (Ch7). There is a problem on doing a program to write a function to accept a string -and output it reversed. ie Bruce --->ecurB
> I'm using the IDLE interface on Win98 (I have Linux but my modem is not working so well on it at the moment). Can you correct my program below and give me some sample program as to how to do it simply. I'm not having trouble with the logic of the string manipulation(I think) - just getting the program to accept input and print output.
> Regards..
> Paul Jones
If you don't care about the algorihm, then you can utilize Python
apropriately.
>>> import string
>>> a = 'spam, spam, eggs and spam'
>>> l = list(a)
>>> l
['s', 'p', 'a', 'm', ',', ' ', 's', 'p', 'a', 'm', ',', ' ', 'e', 'g',
'g', 's', ' ', 'a', 'n', 'd', ' ', 's', 'p', 'a', 'm']
>>> l.reverse()
>>> l
['m', 'a', 'p', 's', ' ', 'd', 'n', 'a', ' ', 's', 'g', 'g', 'e', ' ',
',', 'm', 'a', 'p', 's', ' ', ',', 'm', 'a', 'p', 's']
>>> b = string.join(l, '')
>>> b
'maps dna sgge ,maps ,maps'
>>>
And if you do care about the algorithm, the book will likely have you
looking into recursion.
>>> def string_reverse(s):
... if s:
... # prepend last character to result of string_reverse
... return s[-1:] + string_reverse(s[:-1])
... else:
... return ''
...
>>> string_reverse(a)
'maps dna sgge ,maps ,maps'
>>>
-Arcege
--
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager | Email: arcege@shore.net |
| Salem, Mass. USA 01970 | |
------------------------------------------------------------------------