It feels so good, so quick and not C!
Roy Smith
roy at panix.com
Mon Mar 17 21:27:24 EST 2003
In article <mailman.1047952113.6728.python-list at python.org>,
"BB" <bbondi at pacbell.net> wrote:
> Hi ya'all
> I've been lurking and learning as much as I can. I then decided to do a
> simple project to write a "reverse string" routine. This helped a lot! It
> showed me that I really think in C terms. I am beginning to see the value of
> lists and the simplicity they bring to manipulation of data.
> Anyway, I throwing this piece of code into the arena to be kicked about -
> I hope to learn even more this way.
>
> print "This is a prompt. Enter a string to be reversed: ",
> sOrig = raw_input()#get a string to work on
> sRev=""#init
> char_count=len(sOrig)#now I have the string length
> while ((char_count - 1) >= 0):#loop thru string backwards, zero based
> char_count = char_count - 1
> sRev = sRev+sOrig[char_count]#create the reverse string
> print sRev
>
>
While what you've written will probably work (I'll confess, I havn't run
it myself to make sure), it is a very C-like way of doing things. In
general, anytime in Python you find yourself walking through a sequence
by incrementing an index, you should suspect you're doing something in
an "un-pythonic" way.
I've fallen into that trap more than once, and each time, after I've
recognized the problem and rewritten it pythonicly, I've ended up with
more readable (and often, faster executing) code.
Ignoring for the moment convenient built-ins like reverse(), I'd be
thinking more along the lines of:
reverseList = [] # create an empty list
for c in sOrig: # walk the string, one char at a time
reverseList.insert (0, c) # pushes c onto front of reverseList
sRev = ''.join(reverseList) # squashes list of characters into string
print sRev
More information about the Python-list
mailing list