Stuck in Reverse


#1



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

and Oops, try again. Your code looks a bit off--it threw a "string index out of range" error. Check the Hint if you need help!

I cannot figure out it is out of range. If i is length of text in my examle it should be new_word.join(text[4]), then go down to 3,2,1 and the while loop should stop at 0.


def reverse(text):
    i = len(text)
    new_word=''
    while i >= 0:
        new_word.join(text[i])
        i = i-1
    print new_word
reverse('abcd')


#2

okay, lets say we want to reverse abcd, agree that the length is 4? so i will be 4?

however, strings are zero indexed based so for abcd the indexes are: 0, 1, 2, 3

so text[4] is not a valid index. maybe subtract one to compensate for the zero index base of strings?


#3

Thanks - I was wondering about index number and was unsure if it was string or list that started with 0. However I then tried the following and now I get None instead of the reversed word.
`
def reverse(text):
i = len(text)
new_word=''
while i >= 0:
new_word.join(text[i-1])
i = i-1
print new_word


#5

Looking online I see most solutions with split and [::-1] neither of which I think was taught here yet. Split I get but I do not get the point of the [::-1] at all. Please do not let this side question distract you from helping with the way I am already trying .....


#6

you should return the reversed string (use the return keyword)

[::-1] is blocked by the exercise, it would to easy, you have to develop your own algorithm.


#7

def reverse(text):
    i = len(text)
    new_word=''
    while i >= 0:
        new_word.join(text[i-1])
        i = i-1
    return new_word
reverse('Python!')`

Now it is returning ' ' instead of the intended text. This one is really sticking it to me!


#8

.join() is used if you have a list to join a list together:

print " ".join(["hello","world"])

but new_word is already a string. to join strings simply use +:

x = "hello" + " " + "world"
print x

#9

Thanks. That did it.


#10