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?
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.
simplicis's answer is so good, but here is an easy way to reverse a string like this:
print('Hello'[::-1])
Output:
olleH
for i in range(len(s)-1,-1,-1)insteadreversed(range(len(s)))more readable thanrange(len(s)-1,-1,-1)s[::-1]would also reverse the string.