1

I have this code and I don't why it doesn't print the input string in reversed order. I have specified it to print from the last character of the string to the first character with (-1,0,-1).

string=str(input())

for i in range(-1,0,-1):
    print(string[i],end="")
Yolanda Hui
  • 97
  • 1
  • 1
  • 8

4 Answers4

4

The range(-1, 0, -1) is empty. A range can not work with the fact that -1 will result in the last element, since it does not know the length of the collection (here a string).

So if we convert the range(..) to a list, we get:

>>> list(range(-1, 0, -1))
[]

You thus need to start with len(string)-1, furthermore since the second parameter is exclusive, this should be -1. For example:

>>> string = 'foobar'
>>> list(range(len(string)-1, -1, -1))
[5, 4, 3, 2, 1, 0]

So in your case we can use this like:

for i in range(len(string)-1, -1, -1):
    print(string[i],end="")

An aternative is to use reversed(..), or by slcing the string:

for c in reversed(string):
    print(c, end='')

Note that you better first generate the full string, so for example:

print(string[::-1])

or an alternative (but less performant):

print(''.join(reversed(string))
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
2

Use slice notation to print the string backwards:

print(string[::-1])

The -1 is the step size and direction.

figbeam
  • 7,001
  • 2
  • 12
  • 18
2

As Willem Van Onsem pointed out, range(-1, 0, 1) is empty. If you're looking to print a string in reversed order, it's easier to use string slicing:

print(string[::-1])
Joel
  • 1,564
  • 7
  • 12
  • 20
2

Your range is not defined correctly, as demonstrated by:

for i in range(-1,0,-1):
  print(i)

doesn't return anything. Moreover len(i) returns 0.

Just use list extended syntax here:

string=str(input())
print(string[::-1])
jeannej
  • 1,135
  • 1
  • 9
  • 23