Python | String Palindrome Check

Let’s see What is a Palindrome first and then get into How to check whether some string is palindrome or not using Python Programming Language.
A Palindrome is a word, sequence/phrase which reads same as backward as it does forwards. Words like ‘civic’, ‘radar’, ‘racecar’ are Palindrome. Let’s now write Python Program for checking string is palindrome or not.

Approach 1 => Let’s see steps for writing String Palindrome Check in Python

  1. Make string caseless by calling casefold() function on it using string.casefold() statement
  2. Reverse casefolded string using reversed() function
  3. Turn both string and casefolded reversed string into lists using list() function
  4. Compare these two lists, if lists are equal then strings are palindrome otherwise not

Let’s put together above 4 steps as Python Code. Below is Python Code for checking whether string is Palindrome or not.

a_string = 'radar'

a_string = a_string.casefold()                  # Step 1

rev_a_string = reversed(a_string)               # Step 2

if list(a_string) == list(rev_a_string):        # Step 3 and 4
	print("String is a Palindrome")
else:
	print("String is not a Palindrome")

Approach 2 => Let’s see steps for writing String Palindrome Check in Python

For checking whether String is palindrome or not, we can also loop around string and check if first element is same as last element, second element is same as second last element and so on like this. Let’s see Steps for doing this in Python Code.

  1. Loop around on whole of string using for i in range(0, int(len(str)/2))
  2. While looping on string check if str[i] != str[len(str) – i – 1] (Checking first, second elements are not same as first, second elements from end of string) and Returne False, otherwise always return True
  3. Depending upon True or False returned by above step String would be Palindrome or not

Let’s put all of these steps together as Python Code for Checking String Palindrome or not.

# function to check string is palindrome or not 

def isPalindrome(test_str):
    # Run loop from 0 to len/2 
    for i in range(0, int(len(test_str)/2)): 
        if test_str[i] != test_str[len(test_str)-i-1]:
            return False
    return True

test_str = "Hello"

if (isPalindrome(test_str)):
	print(test_str, "=> is a Palindrome")
else:
	print(test_str, "=> is not a Palindrome")

Approach 3 => Checking Whether string is Palindrome or not using Flag

# Python program to check if a string is palindrome

test_str = 'civic'
j = -1
flag = 0
for i in st:
    if i != st[j]:
      j = j - 1
      flag = 1
      break
    j = j - 1
if flag == 1:
    print(test_str, " => is not a Palindrome")
else:
    print(test_str, " => is a Palindrome")

Approach 4 => Checking Whether string is a Palindrome or not using Recursion

  1. Firstly change string to lowercase using string.lower() Function
  2. Get length of string using len(string) Function
  3. Compare length of string with 2 using if length < 2. In case length of string is < 2 then string is Palindrome
  4. If Step 3 doesn’t come out to be True then compare first, last elements of string using string[0] == string[length – 1] and do this recursively for all elements in string

Let’s Put together all of these 4 steps as Python Code for Checking Whether string is Palindrome or not.

def isPalindrome(testing_str):
    testing_str = testing_str.lower()                              # Step 1
    len_testing_str = len(testing_str)                             # Step 2
    if len_testing_str < 2:                                        # Step 3
        return True
    elif testing_str[0] == testing_str[len_testing_str - 1]:              # Step 4
        return isPalindrome(testing_str[1: len_testing_str - 1])          # Step 4
    else:
        return False
 
testing_str = "ComputerScienceHub"
if (isPalindrome(testing_str)):
    print(testing_str, " => is a Palindrome")
else:
    print(testing_str, " => is not a Palindrome")

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

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

Recent Posts