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

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.

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Earned Value Analysis in Scrum for Dummies

Simple Tools | Diff Checker

How to synchronize MySQL Database with ElasticSearch And perform data querying in a Spring Boot…

Programming From Beginning

How to Participate in FUR’s IDO

Favorite WWDC 2019 sessions

What makes a great Product Manager?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Parvez Alam

Parvez Alam

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

More from Medium

Recognizing Handwritten Digits with Scikit-Learn

Understanding Numpy Array Selection

Error handling techniques in python

Sorting and Searching