Skip to main content
Check if a String is Palindrome in Python

Check if a String is Palindrome in Python

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

Leave a Reply

Your email address will not be published. Required fields are marked *