Thursday, December 22, 2022

Python Program to Check Whether String is Palindrome or Not

This post is about writing a Python program to find whether a given string is a palindrome or not.

A String is a palindrome if reverse of the string is same as the original string. For example "madam" is a palindrome as reverse of the madam is again madam another example is "malayalam".

Logic for the palindrome program

  1. One way to find whether a given string is a palindrome or not is to reverse the given string. If reverse of the string and original string are equal that means string is a palindrome.
  2. Another way is to iterate string and compare characters at both ends (start and end) for equality. Any time if a character is found that is not equal before start > end then it is not a palindrome.

1. Reversing string and comparing

For reversing a string in Python best way is to use string slicing with a negative increment number to get the string backward. Once you have the reversed string compare it with original string to check if both are equal or not.

import re
def reverse_string(string):
  rstring = string[::-1]
  return rstring

def is_palindrome(s):
  rstring = reverse_string(s)
  return True if (rstring == s) else False

s = "madam"
# if more than one word remove spaces
# s = re.sub("^\\s+|\\s+$|\\s+", "", s)
# print(s)
flag = is_palindrome(s)
if flag == 1:
  print(s, 'is a palindrome')
else:
  print(s, 'is not a palindrome')

Output

madam is a palindrome

Note that if string has more than one word like “nurses run” then remove the spaces from the string before checking for palindrome string. You can uncomment the commented lines for that.

2. Comparing characters from start and end of the string

You can also compare characters from both ends of the string, if any time a character is found which is not equal then the passed string is not a palindrome. Python program to find whether given string is a palindrome or not using this logic can be written both as a recursive function and iterative function.

Recursive function is given first.

def is_palindrome(s):
  print(s)
  if len(s) == 0:
    return True
  else:
    if s[0] == s[-1]:
      # remove start and end characters
      return is_palindrome(s[1:len(s)-1])
    else:
      return False

s = "radar"
flag = is_palindrome(s)
if flag == 1:
  print(s, 'is a palindrome')
else:
  print(s, 'is not a palindrome')

Output

radar
ada
d

radar is a palindrome

As an iterative function.

def is_palindrome(s):
  # last index
  end = len(s) - 1;
  for start in range(len(s)):
    # all the characters are compared and are equal
    if start > end:
      return True
    else:
      # compare characters at both ends
      if s[start] == s[end]:
        # move towards left
        end -= 1
      else:
        return False

s = "malayalam"
flag = is_palindrome(s)
if flag == 1:
  print(s, 'is a palindrome')
else:
  print(s, 'is not a palindrome')

Output

malayalam is a palindrome

That's all for this topic Python Program to Check Whether String is Palindrome or Not. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Reverse a String
  2. Python Program to Display Armstrong Numbers
  3. Getting Substring in Python String
  4. Python String isnumeric() Method
  5. Python Generator, Generator Expression, Yield Statement

You may also like-

  1. Ternary Operator in Python
  2. Operator Overloading in Python
  3. Abstract Class in Python
  4. Magic Methods in Python With Examples
  5. Java CountDownLatch With Examples
  6. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
  7. How to Write Excel File in Java Using Apache POI
  8. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation