Reverse


#1



the error message i got is
Oops, try again. Your function fails on reverse("Python!"). It returns "" when it should return "!nohtyP".


Well i thought that my code should be able to take the text input as a string, but somehow it didn't work that way :slight_smile:
Would appreciate some help here


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


#2

if you want to get from higher (len(text)) to lower value 0, range should have a third argument (-1) otherwise it tries +1 steps


#3

Great thanks. I made the following amendments, and now i got this

What does it mean string index out of range?

def reverse(text):
    newstr = ""
    for i in range (len(text),0,-1):
        newstr = newstr + text[i]
        #i-=1
    return newstr
        
print reverse("Python!")

Traceback (most recent call last):
File "python", line 8, in
File "python", line 4, in reverse
IndexError: string index out of range


#4

lets say we want to reverse hello, the length is 5, and the indexes are: 0, 1, 2,3 and 4

so for the first run of the loop, i will be 5. But there is no index 5

so you have to subtract one for the fact that strings are zero indexed based and length start counting at one


#5

Got it. Thank you so much. Yes, should have seen that :grinning:


#7

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