Yolanda Hui
Yolanda Hui

Reputation: 97

How do you modify this code so that it will print the input string in reversed order?

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="")

Upvotes: 1

Views: 94

Answers (4)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

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))

Upvotes: 4

jeannej
jeannej

Reputation: 1192

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])

Upvotes: 2

Joel
Joel

Reputation: 1574

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])

Upvotes: 2

figbeam
figbeam

Reputation: 7176

Use slice notation to print the string backwards:

print(string[::-1])

The -1 is the step size and direction.

Upvotes: 2

Related Questions