I was working on the reverse exercise in the Practice Makes Perfect tutorial for 
Python. I got the function to work with the following code:

def reverse(text):
    length = len(text)
    rev = ''
    while length > 0:
        rev = rev + text[length-1]
        length -= 1
    return rev  

That was my second attempt at a solution. My first attempt looked like this: 
def reverse(text):

  for i in range(length):
        temp = text[i]
        endIndex = length - (i+1)
        text[i] = text[endIndex]
  return text

But it would not work and I kept getting the following error:

"Does your reverse function take exactly one argument (a string)?
 Your code threw a "'str' object does not support item assignment" error."

So I'm wondering if anyone can help me understand why my first attempt doesn't work. 
Can you not edit individual characters of a string like you can items in a list? 


A string in Python is immutable, which means that you can't change its value, nor one of the characters. The best way to work around this, is to start with an empty string and just add your value to this string. At the end you return this string.

Try it yourself, if it doesn't work, feel free to ask a follow-up question.


Ok got it. Thanks for your help!


@nicoekkart, I am not able to understand the error. My code is as following:

def reverse(text):
    text = str(text)
    rev_text = ""
    length = len(text)
    print length
    for i in (0, length):
        j = length - i - 1
        a = str(text[j])
        rev_text = rev_text + a
    return rev_text

abc = reverse("Siddharth")
print abc

Could you please help me out.


You just need to add a range around (0, length) and it will work.


Thank you so much @nicoekkart.
What a silly error from my side.


So, i'm a little confused by your answer.
while length > 0:
rev = rev + text[length-1]
length -= 1


how are you indexing a string? I thought this "list[x]" was for lists. Python allows you to index through a string?


A string is just a list of characters, so yes, you can index it.


Hi there,
Is it right?

def reverse(b):
    l = []
    a = str(b)
    for i in a:
    return c
print reverse("abc")



Seems to work when i run it, so I would say it's correct :smiley:.


This worked for me:

def reverse(text):
    size = len(text)-1
    out = []
    for i in text:
        myout = text[size]
    return ''.join(out)

I know it's messy, so if anyone would like to show me how to tidy it up, I'd be grateful.


This is the code I tried for reversing the letters in a word. Wanted to know where did I go wrong?

def reverse(x):
    for i in x: 
    return new
print reverse(x)