To reverse a given string


#1



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


it shows list assignment index out of range


instead it should reverse the given string


def reverse(text):
    word=[]
    new_word=""
    j=0
    for i in text:
        word[j]=i
        j+=1
    for k in range(j,0):
        new_word=word[k]
    return new_word


#2

here:

word[j]=i

you can use this to update an element in list, but given word is empty, this will throw an error index error

to convert to text to a list, use .append() in the loop


#3

def reverse(text):
    new_text=""
    word=[]
    j=0
    for i in text:
        word.append(i)
        j+=1
    for i in range(j,0):
        new_text.append(word[i])
    return new_text

#4

same error.
above is my code


#5

you got a new error message:

Oops, try again. Your function fails on reverse("Python!"). It returns "" when it should return "!nohtyP".

by default range() will take steps of +1, but if you want to get from higher to lower values you should take steps of -1, give range a third argument of -1

Keep in mind that list and strings are zero indexed based, so j contains the length (for example 5), but then the highest index is 4


#6

I wrote third argument but still it shows "index is out of range error" .


#7

did you do j-1 like i suggested? If you need more help, post an updated version of your code


#8

yeah i wrote (j-1) but then it says your function returns "!nohtyP" instead of "Python!"


#9


#10

def reverse(text):
    new_text=""
    word=[]
    j=0
    for i in text:
        word.append(i)
        j+=1
    for i in range(j-1,0,-1):
        new_text+=word[i]
    return new_text

#11

range() doesn't include the stop value, so having 0 as stop value will mean the first character (the p of Python) won't be added to the reversed string. You need to include index 0


#13

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