Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reverse a String
#1
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
Reply
#2
You need backward iterations over the string here, why do you increment i? (i=i+1)
Reply
#3
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.
Reply
#4
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  printing a string in reverse Skaperen 2 1,505 Nov-20-2021, 05:08 AM
Last Post: ghoul
  I am trying to reverse a string using loop codinglearner 4 2,128 Sep-28-2021, 10:46 PM
Last Post: Pedroski55
  Reverse the string word sneha 2 2,573 Dec-12-2019, 03:37 AM
Last Post: sneha
  String slicing in python from reverse ift38375 1 2,360 Apr-29-2019, 06:58 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020