Reverse


#1



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


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

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 dont have idea how to make it works... Any hints on it? Thank you.


def reverse(text):
    rev_text = []
    i = len(text)
    while i >= 0:
        rev_text.append(text[i])
        print text[i]
        i = i - 1
    return rev_text
    
print reverse("APPLE")


#2

Problem1.
i = len(text)
It will give you out of range error.

hint**
Iteration should be 1 less than length.

Problem2.

rev_text

is a list, you're returning list but you had to return string.
You need to convert the rev_text into string again before you return it.

hint--
use join() function of list to convert it to string again!

an Example--

listX = ['1', '2', '3']
strX = ''.join(list1)

will return "123" (a string)

Note: You can solve it using empty string rather than using empty list.
It will avoid the problem of changing list to string ,and you'll just working at one data type,less bugs!


#3

Wow I got it! Thanks for the help.

However, I am not really understand the problem on:

i = len(text) - 1

because it count from 0 but not 1?

Thank you.


#4

Suppose you input string "netpro11097",
the length function returns 11.

You're iterating the loop and adding to list.
while loop starts with 0 and will go upto 11.

which counts 12?right!

but there should be only 11 items!
do reply if it solves your problem or not!


#5

:smile: Thank you I understand now! Thank you for solves my problem!


#6

You're welcome! :slight_smile:


#7

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