Python Forum

Full Version: Reverse a String
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
HI team,

This is my first post since I started learning Python now and came to know about this forum. Hence I reached out here to get clarifications.

I need to reverse a string and print it, and I have written a code. But it is not complete and prints a different answer when I give the input. I think the loop (i = i + 1) is not executed properly and hence its printing only the alphabhet 'c'. I am not sure of what I am missing here.

May I kindly request this forum to help me fix this issue. I am thankful to you for the effort you have taken for reading thi post.
def reverse(s):
    '''(str) -> str
    Return the reverse of s.
    >>> reverse('abc')
    'cba'
    '''
    str_change = ''
    i = len(s) - 1
    while i >= 0:
        str_change = str_change + s[i]
        i = i + 1
    return result
Thanks,
ragav
You need backward iterations over the string here, why do you increment i? (i=i+1)
Looks pretty close.

If you're going from the back of the list, then you need to decrement the index, not increment it.

Also, you're working with str_change in the loop, but then at the end you try to return result.

Fix those two things and it should be functional.
All, thanks much for your effort to review the same and provide inputs. I am sorry that my post was not as per the Forum expectation, but since I am new to this, the mistake happened. I will ensure that this does not happen in future. I am giving the full code here, but still I get error and not the correct ouput. When I write this code and compile it and run my input in the Python Shell, I get error for this input. And for some reason, I am unable to get the indentation when I post the code (it is indented properly in my shell).

I want to reverse the below string:
reverse ('abc')
Error message I get:
Error:
Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> reverse('abc') File "Final_Miss.py", line 430, in reverse str_change = str_change + s[i] IndexError: string index out of range
My code snippet:
def reverse(s):
    '''(str) -> str
    Return the reverse of s.
    >>> reverse('abc')
    'cba'
    '''
    str_change = ''
    i = len(s) - 1
    while i >= 0:
        str_change = str_change + s[i]
        i = i + 1
    return str_change