Skip to content
scipython.com

P2.7.7Determine if a string is a palindrome using recursion

Write a function that determines if a string is a palindrome (that is, reads the same backwards as forwards) using recursion.

Show solution

The function defined in the code listing below is explained in its comments.

def is_palindrome(s):
    """ Return True is s is a palindrome, else return False. """
    if len(s) < 2:
        return True
    # Return False unless the first and last letters of s are the same
    # and the substring between them is a palindrome
    return s[0] == s[-1] and is_palindrome(s[1:-1])

test_words = ('thatch', 'minim', 'an', 'i', 'redder')
for word in test_words:
    print('Is "{:s}" a palindrome:'.format(word), is_palindrome(word))

Output:

Is "thatch" a palindrome: False
Is "minim" a palindrome: True
Is "an" a palindrome: False
Is "i" a palindrome: True
Is "redder" a palindrome: True