7: Reverse


#1

So my code words but I don't know why.

def reverse(text):

    rever = []
    text = str(text)
    n = len(text) - 1

    text = list(text)
    print text
    
    final = ""
    while n >= 0:
        final += str(text[n])
        n = n - 1

    return final

print reverse("examples")

I originally has it as n = len(text) but then I got an error that "list index is out of range"
making it len(text) -1 fixes the error but Im not sure why...

I know my code isn't neat or efficient and doesn't look like others peoples answer to this question but its the only way I could work out how to do it.

Thanks for any help


#2

let's say i have a string: "hello", hello is 5 characters, but strings are zero indexed based, the first letter (h) is at position 0. so o (the last letter) would be at position 4. so length returns 5, but the last letter is indexed at 4, so that is why you need minus 1


#3

ah, I thought that it would return hello as 4 characters. Dealing with counting from 0 and from 1 is confusing...
Thanks for the help