7. reverse


#1




"string index out of range"


def reverse(text):
    for i in range(0, len(text)/2):
        text[i] = text[len(text) - i]
    return text
    
reverse("abcd")


#2

strings are zero indexed based, for example:

h   e   l   l   o
0   1   2   3   4

make sense? also agree that len("hello") is 5. lets do the first iteration of your for loop for hello:

text[0] = text[5 -0]

hm... hello doesn't have an index 5, this is why you get an index out of range index, hopes this helps


#3

Thanks for your help. However, I corrected the code as following:

def reverse(text):
    for i in range(0, len(text)/2):
        text[i] = text[len(text) - 1 - i]
    return text
    
reverse("abcd")

The following error message shows up:
'str' object does not support item assignment


#4

in python strings are immutable. So this:

text[i]

to manipulate a string is not possible. you could do that if you have a list, but it won't work for strings

why do you divide by 2? this will mean a lot of characters get skipped


#5

That is possible as a read only.

text[i] = ...

Is not possible. Just to clarify.


#6

edited


#7

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