Written by Eric Roberts, adapted by Chris Piech

This program determines if a given string is a palindrome. A string is a palindrome if it is the same forward as backwards, disregarding punctuation, capitalization and whitespace. For example:

  • Abba
  • Racecar
  • Kayak
  • Mr. Owl ate my metal worm.
  • Go hang a salami! I'm a lasagna hog.
  • Elu par cette crapule


Our strategy is simple, we are going to perform two steps. First we are going to normalize the given string: remove whitespace and non-alpha characters and making the string lowercase. Then we are going to test if the normalized string is == to the reverse of the normalized string. Simple. Elegant. Effective.


# some examples
SIMPLE = 'kayak'
KOREAN = '여보, 안경 안보여'
OWL = 'Mr. Owl ate my metal worm.'
HINDI = 'कडक'

def main():
    original = HINDI

    if is_palindrome(original):
        print('Is a palindrome of length ' + str(len(original)) + ' characters')
        print('Is not a palindrome...')

def is_palindrome(str):
    >>> is_palindrome('racecar')
    >>> is_palindrome('chris')
    normalized = normalize(str)
    rev = reversed(normalized)
    return normalized == rev

def normalize(str):
    >>> normalize('abc ! def')
    >>> normalize('여보, 안경')
    normalized = ''
    for ch in str:
        if ch.isalpha():
            normalized += ch.lower()
    return normalized

def reversed(str):
    Takes a string and returns a reversed copy
    >>> reversed('stressed')
    >>> reversed('hello')
    return str[::-1]

if __name__ == '__main__':