0
def reverse(text):
    length = len(text)
    length -= 1
    a = ''
    for pos in range(length/2):
        a[pos] = text[length]
        text[pos] = a[pos]
        length -= 1
    print text

While I was coding in codecademy I typed this code and found the error which is:

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

which step am I doing wrong? how to proceed without using .join() or any in-built?

3
  • Strings are immutable, you can't assign to a character by index. Commented Feb 15, 2016 at 20:44
  • strings are immutable so you cannot use assignment as you would a list, why not just concat to a starting in range len(s) down ? Commented Feb 15, 2016 at 20:44
  • It looks like you expect this to be swapping characters in your string; even if strings were mutable, this wouldn't accomplish that. Commented Feb 15, 2016 at 20:47

3 Answers 3

2

It's as simple as this:

text[::-1]
Sign up to request clarification or add additional context in comments.

2 Comments

I am not allowed to use [: :-1] or reversed sir
A simple solution without any slicing or built-ins: result = ''; for c in text: result = c + result
0

Strings are immutable, you have to create a new one.

Try:

def reverse(text):
    length = len(text)
    a = ''
    for pos in range(length):
        a += text[length-pos-1]
    print a

Comments

0

As I commented strings as immutable and do not support assignment as a mutable structure like a list does, you can use a range starting from the length of the string -1 to 0 and concat each character to your a string:

def reverse(text):
    length = len(text) - 1
    a = ''
    for pos in range(length,-1,-1):
        a += text[pos]
    return a

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.