Check if a String is Palindrome in Python — pythonpip.com

Parvez Alam
2 min readJan 23, 2022

In this tutorial, you’ll learn how to use Python to check if a string is a palindrome. We’ll discuss different ways to check palindrome strings.

What’s Palindrome String

A palindrome is a word, phrase, number, or sequence of words that reads the same backward as forward.

Check Palindrome String Using lower() and reverse() method

To check if a string is a palindrome in Python, use the lower() and reversed() method.

Sample Python program:

# test.py str = 'madam' # make it suitable for caseless comparison str = str.lower().replace(' ', '') # reverse the string rev_str = ''.join(reversed(str)) # check if the string is equal to its reverse if list(str) == list(rev_str): print("palindrome") else: print(" not palindrome")

Output:

palindrome

Check Palindrome String Using casefold() and reverse() method

To check if a string is a palindrome in Python, use the casefold() and reversed() method.

Sample Python program:

# test.py str = 'madam' # make it suitable for caseless comparison str = str.casefold() # reverse the string rev_str = reversed(str) # check if the string is equal to its reverse if list(str) == list(rev_str): print("palindrome") else: print(" not palindrome")

Output:

palindrome

Check if a Number is a Python Palindrome

Converting a number to a string and using any of the methods listed above is the simplest approach to see if it’s a Python palindrome.

Sample Python program:

a_number = 123454321 number = str(a_number) if number == number[::-1]: print("palindrome") else: print(" not palindrome")

Output:

palindrome

Originally published at https://www.pythonpip.com on January 23, 2022.

--

--

Parvez Alam

Hey, I am Parvez Alam. A software developer since 2009. I love learning and sharing knowledge. https://www.phpflow.com/