Reputation: 2115
I want to reverse a string like so:
def reverse(s):
for i in range(len(s),0,-1):
var = s[i] # getting an out of range error?
...
Can someone explain why?
Upvotes: 2
Views: 730
Reputation: 6467
If a string length is n
, the valid indexes are from 0
to n-1
(the elements are counted from 0 not from 1).
In your code the for
loop condition len(s)
should be changed into len(s) - 1
.
Upvotes: 3
Reputation: 22292
simplicis's answer is so good, but here is an easy way to reverse a string like this:
print('Hello'[::-1])
Output:
olleH
Upvotes: 1