String index out of range- dont know why. can somebody help


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096

it says 'string index out of range'


def reverse(text):
    l=len(text)
    rev=[]
    print range(l)
    for i in range(l):
        rev=rev+ text[l-i+1]
    return rev
    print rev
reverse("python")


#2

i added a print statement to your code:

def reverse(text):
    l=len(text)
    rev=[]
    print range(l)
    for i in range(l):
        print l,i
        rev=rev+ text[l-i+1]
    return rev
    print rev
print reverse("python")

as you can see, l is 6 (make sense, the length is 6), i is zero. so then this line:

rev=rev+ text[l-i+1]

which means you try to access index 7 in the first run of your loop:

text[7]

That is going to be a problem. your letters are indexed at 0,1,2,3,4,5. This is the problem. I recommend to try and solve it yourself first now you seen where the problem is, if you need more help post an updated version of your code