Palindrome in Python

Let’s examine how to determine whether a word or sentence is palindrome or not in python.

Words and/or sentences are palindrome when you can read them from beginning to end and vice versa and have the same meaning. In the case of sentences, we don’t consider the spaces and punctuation.

Some examples are:

  • Civic
  • Radar
  • Kayak
  • “Was it a car or a cat I saw?”

Python program to determine if a word is a palindrome

With the code below, we can determine if a word is palindrome or not.

def palindrome(word):
    word = word.lower()
    n = len(word)
    for i in range(int(n/2)):
        if word[i]!=word[n-1-i]:
            return False
    return True

Notice that we first convert the word to lowercase, to avoid a false negative because of uppercase letters.

Then, with a for loop for half of the word is enough. We use the loop variable i and compare the character in position i with the one in position n-i.

As a result, we will compare the first character with the last one, the second with the second last, and so on. Notice that is not necessary to check if the word has an odd number of characters.

Python program to determine if a sentence is a palindrome

To determine if a sentence is palindrome or not, we can use almost the same code that we used in the section before.

However, we need to “clean up” the sentence because punctuation and spaces are not considered.

First, we create an auxiliary function to clean up the sentence.

def cleanup(word):
    word = word.replace(' ','')
    word = word.replace('!','')
    word = word.replace('?','')
    word = word.replace(',','')
    word = word.replace('.','')
    return word.lower()

As you can see, we remove spaces and punctuation from the sentence and convert it to lower case.

After that, we use almost the same code that we used for the words.

def palindrome(word):
    word = cleanup(word)
    n = len(word)
    for i in range(int(n/2)):
        if word[i]!=word[n-1-i]:
            return False
    return True

And as usual, we use a console python program to test the implementation.

if __name__=='__main__':
    word = input('Enter a string: ')
    print (palindrome(word))

H@ppy coding!

Related posts: