patrickhuang94
patrickhuang94

Reputation: 2115

Python string index out of bounds

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

Answers (2)

Ziezi
Ziezi

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

Remi Guan
Remi Guan

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

Related Questions