Write a program in python to count all palindrome words present in a sentence or string.


For this, we need to loop through each word in the sentence and compare each word with its corresponding reverse. If they are equal then we will increment the count.

In python a word can be easily reversed by word[::-1]

Instead of counting, we will store all the palindrome words in a list, so that it can be printed or used for other purposes.

l=[]  #empty list

st="mom and dad are going to malayalam"

#looping through each word in the string
for word in st.split():
    #if word is equal to its reverse then it is palindrome
    if word==word[::-1]:
        l.append(word)    #add word to list

print("Total  number of palindrome words in a sentence: ",len(l))


If you have any suggestions or doubts then comment below.

This Post Has One Comment

  1. Anirudh Kumar
    # Python3 program to count number of  
    # palindrome words in a sentence 
    # Function to check if a word is palindrome 
    def checkPalin(word): 
        if word.lower() == word.lower()[::-1]: 
            return True
    # Function to count palindrome words 
    def countPalin(str): 
        count = 0
        # splitting each word as spaces as  
        # delimiter and storing it into a list 
        listOfWords = str.split(" ") 
        # Iterating every element from list  
        # and checking if it is a palindrome. 
        for elements in listOfWords: 
            if (checkPalin(elements)): 
                # if the word is a palindrome  
                # increment the count. 
                count += 1
        print (count) 
    # Driver code 
    countPalin("Madam Arora teaches malayalam") 
    countPalin("Nitin speaks Malayalam")

Leave a Reply

twenty − 13 =