Open In App

Python Program to Check if a String is Palindrome or Not

Last Updated : 20 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string, write a python function to check if it is palindrome or not. A string is said to be a palindrome if the reverse of the string is the same as the string. For example, “radar” is a palindrome, but “radix” is not a palindrome.

Examples: 

Input : malayalam
Output : Yes
Input : geeks
Output : No

Python Program to Check if a String is Palindrome or Not Using Native Approach

Here we will find reverse of the string and then Check if reverse and original are same or not.

Python
# function which return reverse of a string

def isPalindrome(s):
    return s == s[::-1]


# Driver code
s = "malayalam"
ans = isPalindrome(s)

if ans:
    print("Yes")
else:
    print("No")

Output
Yes

Time complexity: O(n)
Auxiliary Space: O(1)

Check if a String is Palindrome or Not Using Iterative Method

Run a loop from starting to length/2 and check the first character to the last character of the string and second to second last one and so on …. If any character mismatches, the string wouldn’t be a palindrome.

Below is the implementation of above approach: 

Python
# function to check string is
# palindrome or not
def isPalindrome(str):

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

# main function
s = "malayalam"
ans = isPalindrome(s)

if (ans):
    print("Yes")
else:
    print("No")

Output
Yes

Time complexity: O(n)
Auxiliary Space: O(1)

Check String is Palindrome or Not Using the inbuilt function to reverse a string

In this method, the predefined function ‘ ‘.join(reversed(string)) is used to reverse string. 

Below is the implementation of the above approach: 

Python
# function to check string is
# palindrome or not
def isPalindrome(s):

    # Using predefined function to
    # reverse to string print(s)
    rev = ''.join(reversed(s))

    # Checking if both string are
    # equal or not
    if (s == rev):
        return True
    return False

# main function
s = "malayalam"
ans = isPalindrome(s)

if (ans):
    print("Yes")
else:
    print("No")

Output
Yes

Time complexity: O(n)
Auxiliary Space: O(n)

Check String is Palindrome using one extra variable

In this method, the user takes a character of string one by one and store it in an empty variable. After storing all the characters user will compare both the string and check whether it is palindrome or not. 

Python
# Python program to check
# if a string is palindrome
# or not

x = "malayalam"

w = ""
for i in x:
    w = i + w

if (x == w):
    print("Yes")
else:
    print("No")

Output
Yes

Time complexity: O(n)
Auxiliary Space: O(n)

Check String is Palindrome using flag

In this method, the user compares each character from starting and ending in a for loop and if the character does not match then it will change the status of the flag. Then it will check the status of the flag and accordingly and print whether it is a palindrome or not.  

Python
# Python program to check
# if a string is palindrome
# or not
st = 'malayalam'
j = -1
flag = 0
for i in st:
    if i != st[j]:
        flag = 1
        break
    j = j - 1
if flag == 1:
    print("NO")
else:
    print("Yes")

Output
Yes

Time complexity: O(n)
Auxiliary Space: O(1)

Check String is Palindrome using recursion

This method compares the first and the last element of the string and gives the rest of the substring to a recursive call to itself. 

Python
# Recursive function to check if a
# string is palindrome
def isPalindrome(s):

    # to change it the string is similar case
    s = s.lower()
    # length of s
    l = len(s)

    # if length is less than 2
    if l < 2:
        return True

    # If s[0] and s[l-1] are equal
    elif s[0] == s[l - 1]:

        # Call is palindrome form substring(1,l-1)
        return isPalindrome(s[1: l - 1])

    else:
        return False

# Driver Code
s = "MalaYaLam"
ans = isPalindrome(s)

if ans:
    print("Yes")

else:
    print("No")

Output
Yes

Time complexity: O(n)
Auxiliary Space: O(n)

Python Program to Check if a String is Palindrome or Not – FAQs

What is a strong number in Python?

A strong number (or Krishnamurthy number) is a number whose sum of the factorial of its digits equals the original number. For example, 145 is a strong number because 1!+4!+5!=1+24+120=145.

What are any four palindrome words?

  1. “racecar”
  2. “level”
  3. “radar”
  4. “civic”

How do you identify a palindrome function?

A function correctly checks for palindromes if it returns True for strings that read the same forward and backward and False otherwise. Test it with known palindromes (e.g., “madam”) and non-palindromes (e.g., “hello”).

Can I use slicing or reversing techniques to check for palindromes?

Yes, you can use slicing (s == s[::-1]) or reversing techniques (s == ''.join(reversed(s))) to check if a string is a palindrome. Both methods compare the string with its reverse to determine if it reads the same forward and backward.

How to write a Python program to check whether a string is palindrome or not using a stack?

Here’s a Python program that checks whether a string is a palindrome using a stack:

def is_palindrome(s):
stack = []

# Push all characters to the stack
for char in s:
stack.append(char)

# Pop characters from the stack and compare with the original string
for char in s:
if char != stack.pop():
return False

return True

# Example usage
string = "racecar"
print(f"{string} is a palindrome: {is_palindrome(string)}") # Output: True

string = "hello"
print(f"{string} is a palindrome: {is_palindrome(string)}") # Output: False





Previous Article
Next Article

Similar Reads

Python Program To Check String Is Palindrome Using Stack
A palindrome is a sequence of characters that reads the same backward as forward. Checking whether a given string is a palindrome is a common programming task. In this article, we will explore how to implement a Python program to check if a string is a palindrome using a stack. Example Input: str = “geeksforgeeks” Output: NoInput: str = “madam” Out
3 min read
Python program to check whether the string is Symmetrical or Palindrome
Given a string. the task is to check if the string is symmetrical and palindrome or not. A string is said to be symmetrical if both the halves of the string are the same and a string is said to be a palindrome string if one half of the string is the reverse of the other half or if a string appears the same when read forward or backward. Example: In
6 min read
Python program to check whether number formed by combining all elements of the array is palindrome
Given an array arr[], the task is to combine all the elements in the array sequentially and check if it is a palindrome. Examples: Input: arr[] ={1 , 69 , 54 , 45 , 96 , 1} Output: palindrome Explanation: The number formed by combining all the elements is "1695445961" which is a palindrome Input: arr[] ={2 , 73 , 95 , 59 , 96 , 2} Output: not palin
4 min read
Python program to check if number is palindrome (one-liner)
In this article, we are given a number and we have to check whether the number is palindrome or not in one-liner code. The output will be True if it's a Palindrome number otherwise it would be False. Let's discuss how to find whether a number is palindrome or not in this article. Input1: test_number = 12321 Output1: True Input2: test_number = 1234
3 min read
Python Program To Check If A Singly Linked List Is Palindrome
Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. METHOD 1 (Use a Stack): A simple solution is to use a stack of list nodes. This mainly involves three steps.Traverse the given list from head
6 min read
Python Program to Check if String is Empty or Not
Python strings are immutable and have more complex handling when discussing their operations. Note that a string with spaces is actually an empty string but has a non-zero size. This article also discussed that problem and the solution to it. Let's see different methods of Check if String is Empty Python. Example Input:[" "]Output: YesExplanation:
8 min read
Python program to check if a given string is Keyword or not
Given a string, write a Python program that checks if the given string is keyword or not. Keywords are reserved words which cannot be used as variable names.There are 33 keywords in Python programming language.(in python 3.6.2 version) Examples: Input: str = "geeks" Output: geeks is not a keyword Input: str = "for" Output: for is a keyword We can a
3 min read
Python Program to check whether Characters of all string elements are in lexical order or not
Given a list with string elements, the task is to write a Python program to return True if all list elements are sorted. The point of caution here is to keep in mind we are comparing characters of a string list element with other characters of the same list element and not string elements with each other. Examples: Input : test_list = ["dent", "flo
4 min read
Largest palindrome not exceeding N which can be expressed as product of two 3-digit numbers
Given a positive integer N, the task is to find the largest palindromic number less than N and it can be expressed as the product of two 3-digit numbers. Examples: Input: N = 101110Output: 101101Explanation: The number 101101 ( = 143 * 707) is the largest palindromic number possible satisfying the conditions. Input: N = 800000Output: 793397Explanat
6 min read
Check if Binary representation is Palindrome in Python
Given an integer ‘n’, write a Python function that returns true if binary representation of x is palindrome else return false. Examples: Input : n = 9 Output : True Binary representation of n=9 is 1001 which is palindrome as well. Input : n = 10 Output : False Binary representation of n=10 is 1010 which is not palindrome. We have existing solution
4 min read
Practice Tags :