Reverse a string


#1



def reverse(word):
    backWord = []
    chars = len(word)
    for c in range(chars):
        backWord.append(word[chars - c - 1])
        print backWord
    return ''.join(backWord)

This code works, but I was curious as to what better ways I could approach this problem. I had this exact question in one of my classes one time (except in javascript) and my professor mentioned I could probably do the same thing with a string as opposed to an array. What would that look like? Also I know there has to be a shorter algorithm to this as well. I just wanted to get this out here to help whoever might be stuck on this as well as get feed back. Thank you!!


#2

Reversing is built-in behaviour in python, you'd just slice it backwards and there's no python code that could do it better.
JS strings are immutable (as are python ones) so no, you can't reverse in-place. If you use += to "add" characters then the language implementation may be doing "what you want" but it would be doing something other than what you wrote to accomplish that and you might not even want to rely on that being done for you so you might instead want to write what you meant.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.