Oliver Child-Lanning
Oliver Child-Lanning

Reputation: 25

Keep encountering "string index out of range' error in Python

I'm doing an assignment for an intro course in which I need to determine whether a string is a palindrome. Having trouble with this segment of the code:

    def is_palindrome(letters): 
         if (len(letters))==0:
             return True
         elif len(letters)==1:
             return True
         elif (letters[end])==(letters[0]):
            return is_palindrome(letters[(letters[0+1]):(letters[len(letters)-1])])
         else:
            return False

Upvotes: 0

Views: 39

Answers (2)

Remi Guan
Remi Guan

Reputation: 22282

Try these following codes:

def palindrome(text):
    if text == text[::-1]:
        print(text, 'is palindrome')
    else:
        print(text, 'is not palindrome')

palindrome('reser')
palindrome('reset')

str[::-1] will reverse the string. for more info, try help(slice).

Upvotes: 2

Reblochon Masque
Reblochon Masque

Reputation: 36662

Your code is nearly correct, but you have errors in the slicing of the strings:

def is_palindrome(letters): 
    if (len(letters))==0:
        return True
    elif len(letters)==1:
        return True
    elif (letters[0])==(letters[-1]):       # index [-1] gives the last letter
        return is_palindrome(letters[1:-1]) # slice [1:-1] is the word without the first and last letter.
    else:
        return False

The above works.

I suggest you review this post that explains in details how slicing works: Explain Python's slice notation

Upvotes: 2

Related Questions