7/15 "String index out of range" when referring to char[index]


#1

dear all,

my code looks like this:

def reverse(text):
x = str(text)
for char in x:
a = 0
while a < len(x):
char[a] = char[len(x) - a - 1]
return char
a += 1


and it shows string out of index, but I don't know why.
it would be grateful if someone could help me, thanks!


#2

len("word") = 4 but index starts at 0 so you need to increment from 0 to len("word") - 1


#3

Sorry I could not get your original code to work at all. Fixing the string out of index error threw other errors. Take a look at this and see if it helps you modify your answer:

def reverse(text):
    l = len(text) - 1
    rev = ""
    while l >= 0:
        rev = rev + text[l]
        l = l - 1
    return rev

#4

Thanks a lot!!!
Now I know what went wrong~


#5

Watch out for indexes, thats why -1, -1 -1

def reverse(text):
    grr = ''
    for char in xrange(len(text)-1, -1, -1):
        grr += text[char]
    return grr