Help.. need explanation for the given code


Can someone explain me the code given below

def reverse(text):
    placeholder = ""   
    for item in text:
        placeholder = item+placeholder
    return placeholder

the code is taken from this post

The exercise is about reversing the given string, i got confused and searched the forum and got the above code. It looks simple and works fine(tried using python idle) but i can't understand how does it works(reverse strings)

Replace this line with your code.


using someone else his code, and then get it explained reduces how much you learn from it

this program will loop over text and prepend to placeholder, causing the string to reverse


Hi Sir,
i tried my own code it gave me error. So i searched forum and got the above code which i can't understand how it reverses the string(while the code looks like it just returns the string as it is). So i copied the code and created new post(I did not use it on my exercise ).

here is my code which gave me error:

def reverse(text):
    c = str(text)
    a = ""
    b = range(len(text), 0, -1)
    for i in b:
        a = a + c(i)
    return a


Oops, try again. Does your reverse function take exactly one argument (a string)? Your code threw a "'str' object is not callable" error.



a = a + c(i)

i is an index, to access string by index use square brackets, parentheses is for function calls


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