3

I tried to reverse the string using following code !

def rev_string(text):
    a = len(text)
    for i in range(a,0,-1):
        print(text[i])

rev_string("Hello")

It shows the following error:

  Traceback (most recent call last):
  File "rev_str.py", line 5, in <module>
    rev_string("Hello")
  File "rev_str.py", line 4, in rev_string
    print(text[i])
IndexError: string index out of range

I also tried this code But the last character of the string couldn't be printed.

def rev_string(text):
    a = len(text)
    for i in range(a-1,0,-1):
        print(text[i])
rev_string("Hello")

Output:

python3 rev_str.py
o
l
l
e

Anyone, please help!

utengr
  • 3,225
  • 3
  • 29
  • 68
Vimal Raj
  • 474
  • 6
  • 19
  • There is another way to do exactly what is asked for and not yet answered. This question is not an exact duplicate of #931092, strictly speaking. Here, @Vimal adds an extra `\n` after each character. So a complete and pythonic way can be something like: `print('\n'.join("Hello"[::-1]))` . There may be other answers there, so it might be closed too fast. – emi Oct 26 '17 at 20:34
  • @kvorobiev: this may be a duplicate, but of an "off-by-one" mistake, not the currently linked "Reverse a string in Python" – hunteke Oct 27 '17 at 13:47

4 Answers4

2

This is an "off-by-one" error. Look at your string manually, and then compare with the output of range manually. Note, as you do this, that Python follows C's convention of 0-based indexes. So:

>>> test = 'ABCDE'
>>> print('The first character is: -->{}<--'.format(test[0]))
The first character is: -->A<--
>>> a = len( test )
>>> [i for i in range(a, 0, -1)]
[5, 4, 3, 2, 1]
>>>

Whoops! Where's 0? Hmm, well, let's try index 5:

>>> test[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

So, as this feels like a homework problem, I'll not give an exact solution, but leave with "Given the above, how would you solve it?"

If this is not a homework question, consider other methods of reversing strings that have already been implemented ("Why reinvent the wheel?!")

hunteke
  • 3,648
  • 1
  • 7
  • 17
1

You can use extended slice https://docs.python.org/2/whatsnew/2.3.html#extended-slices

str = 'hello world'
print(str[::-1])
>>>dlrow olleh
Juan
  • 477
  • 4
  • 8
0

a = len(text) returns number of characters in text. For "Hello" a is equal to 5 and the characters in text are indexed from 0 to 4 like text[0] = 'H', text[1] = 'o', text[2] = 'l', text[3] = 'l' and text[4] = 'o'. So text[5] is invalid. Now lets look at how range function generates number:

range(start, stop, step)

start: Starting number of the sequence.

stop: Generate numbers up to, but not including this number.

step: Difference between each number in the sequence.

range(4, 0, -1) generate number 4, 3, 2, 1

range(4, -1, -1) generate number 4, 3, 2, 1, 0

range(4, -2, -1) generate number 4, 3, 2, 1, 0, -1

So you range should be like:

rev_string(text):
    a = len(text)
    for i in range(a-1,-1,-1):
        print(text[i])
rev_string("Hello")
jimidime
  • 542
  • 3
  • 5
0

Just another way to do it.

def rev_string(text):
    a = len(text)
    for i in range(1, a+1):
        print(text[a-i])
rev_string("Hello")

Output:

o
l
l
e
H

How it works:

range(1, a+1) produces range(1,6) = [1,2,3,4,5]

a = 5

Loop iterations:

iteration 1: i = 1, a-i = 5-1 = 4, text[4] = o 
iteration 2: i = 2, a-i = 5-2 = 3, text[3] = l 
iteration 3: i = 3, a-i = 5-3 = 2, text[2] = l 
iteration 4: i = 4, a-i = 5-4 = 1, text[1] = e 
iteration 5: i = 5, a-i = 5-5 = o, text[0] = H 
utengr
  • 3,225
  • 3
  • 29
  • 68