Python Tutorials

Python Programs

Python Check Whether a String is Palindrome or Not


Python Check Whether a String is Palindrome or Not

In this tutorial, we will learn how to check whether a string is a palindrome or not in Python. We will cover the definition of a palindrome and implement a function to check if a given string is a palindrome.


What is a Palindrome

A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Examples of palindromes include 'madam', 'racecar', and '12321'.


Syntax

The syntax to check if a string is a palindrome in Python is:

def is_palindrome(s):
    s = s.replace(" ", "").lower()
    return s == s[::-1]


Checking if a string is a palindrome

We can create a function to check if a given string is a palindrome by comparing it to its reverse.

For example,

  1. Define a function named is_palindrome that takes one parameter s.
  2. Remove any spaces from the string and convert it to lowercase.
  3. Check if the string is equal to its reverse. If true, return True, otherwise return False.
  4. Call the function with a sample string and print the result.

Python Program

def is_palindrome(s):
    s = s.replace(" ", "").lower()
    return s == s[::-1]

# Check if 'Racecar' is a palindrome
result = is_palindrome('Racecar')

# Print the result
if result:
    print("'Racecar' is a palindrome")
else:
    print("'Racecar' is not a palindrome")

Output

'Racecar' is a palindrome