Write a program in python to count all palindrome words present in a sentence or string.
Example:
Input: "mom and dad are talking" Output: 2 Input: "mom and dad are going to malayalam" Output: 3
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))
Output
Total number of palindrome words in a sentence: 3
If you have any suggestions or doubts then comment below.
This Post Has One Comment