The problem asks me to reverse a string without using reversed or [::-1]. I think my code should work but I keep getting the "string index out of range error". If someone could help me out, that would be great. Thanks!

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


Then you'll probably want to investigate the indexes that you use. How can you do that?


The last letter of the text is at index len(text)-1 and not at len(text), which is what you do by taking range(len(text), 1, -1). A possible solution is to do result += text[i-1]


You are right, as you said, the last letter of the text is at len(text)-1. I test it and find something wrong: the first letter of original text is missing. pay attention to range functionrange(start,end), it will not include the end index.So I just change 1 to 0, then it works.


def reverse(text):
---result = ""
---for i in range(len(text), 0, -1): // range should end at index 0
------ result += text[i - 1]
---return result
text = "this is an example"
print reverse(text)


You still need the element at index 0. So the last index in the range function should be -1


Oh oops, that was very simple. Thanks!


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