7. Reverse


Replace this line with your code.


I didn't mean to make a help page. Please ignore this and move on.


what did you intent? Or shall i remove the topic?


I was going to open a help discussion on the page but it wasn't suppose to be "15. Practice makes perfect" It was suppose to be "7. Reverse" Can we talk about it even though the topic is wrong?


your topic is perfectly placed? the python courses contain different section, under each section there are a couple of exercises, 7. reverse is an exercise part of the practice makes perfect section

You can post your question + code + error message in this topic. Or if you just have a question in general about reverse


Ok, thanks. I will do that now. Give me a sec...


This is my code:

def reverse(text):
    number = len(text)
    while number > 0:
        new_text = []
        number - 1
    return new_text

I always get an error saying "string index out of range"
Any ideas on what I am doing wrong?


(Btw I already did the indents properly, I copied and pasted my code to the site but it got rid of the indents)


you need markup to make the indent show:

anway, lets say the string we want to reverse is "hello", then the length of hello is 5, make sense? however, indexes are zero index bases (counting start at zero) so if you have a length of 5, the indexes are: 0, 1, 2, 3, 4.

so when you try to do:


you have a problem, there is no index 5.

You are experiencing this problem. because here you get the length:

number = len(text)

and then here:


you can't, because of this zero based indexes


Isn't there a command in python to get rid of the zero index in replacement for 1?


no? strings and lists will always be zero index based. you could simply subtract one of length to overcome this problem?


Subtract? wont that leave me with [0, 1, 2, 3]?


of the length, not the indexes:

length = len("hello") -1

this way, the length matches to the last index


Oh ok. I will try that out and see if it works


def reverse(text):
number = len(text) - 1
while number > 0:
new_text = []
number - 1
return new_text

Now this code is saying "'str' object has no attribute 'pop'"
Should I get rid of the ".pop" command?


Or is the "- 1" suppose to replace the ".pop" command?


in python strings are immutable, they can't be manipulated.

.pop() is for lists, not for strings. so using pop() won't work. You will need to find a different approach.

the simplest (maybe not the most efficient approach) is to loop over text and prepend them to a string:

result = ""
for i in text:
  result = i + result


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