Python - How To Check if a String Is a Palindrome in Python

ID : 60

viewed : 132

Tags : PythonPython String

vote vote

96

This tutorial discusses the methods to check if a string is a palindrome in Python.

Check if a String Is Palindrome Using the List Slicing Method in Python

A Palindrome string is a word that reads the same forwards and backwards. For example, the word madam remains the same if we reverse the sequence of letters in it; this type of word is called a Palindrome.

We can check for Palindrome strings by reversing the original string and comparing each element of the original string with each element of the reversed string; this can be done with list slicing. The following program below shows us how to check whether a string is a Palindrome or not with the list slicing method.

word = input() if str(word) == str(word)[::-1] :     print("Palindrome") else:     print("Not Palindrome") 

Output:

ma#am Palindrome 

We checked whether the string ma#am is a Palindrome or not with the list slicing method in the code above. We first calculated the reverse value of the original word with [::-1] as the list index. We then compared each index with the equality operator ==. If both the original and reversed words match, we print Palindrome on the console; if not, we print Not Palindrome.

Check if a String Is Palindrome Using the reversed() Function in Python

The takes a sequence of elements and returns a reverse iterator for that sequence. Since a string is a sequence of characters, we can also use the reversed() function in place of the [::-1] list index to reverse the sequence of characters inside a string. We can then compare both original string and reversed string, element-wise, to determine whether it’s a Palindrome or not. The following program snippet demonstrates how to check whether a string is a Palindrome or not with the reversed() function.

word = input() if str(word) == "".join(reversed(word)) :     print("Palindrome") else:     print("Not Palindrome") 

Output:

maisam Not Palindrome 

We checked whether the string maisam is a Palindrome or not with the reversed() function in the program above. We first calculated the reverse form of the original word with "".join(reversed(word)). After that, we compared both the original and the reversed word, element-wise, with the equality operator ==. If both the original and reversed words match, we print Palindrome on the console; if not, we print Not Palindrome.

  • Related HOW TO?