How to Check if a Python String is a Palindrome

How to Check if a Python String is a Palindrome

6 mins read79K Views Comment
clickHere
Updated on Jan 22, 2024 11:57 IST

A palindrome is a sequence of the word, phrases, or numbers that read the same backward as forward. In this article, we will discuss different methods of checking if a string is a palindrome in Python or not.

2022_06_Palindrome.jpg

If you’re a beginner in Python working on your coding skills, one of the most common programs you will come across during your practice sessions is determining whether a given string is a palindrome or not.

We will be covering the following sections today: 

But first, for the unaware, let’s talk about what a palindrome really is, shall we? 

What is a Palindrome? 

A palindrome is a sequence of characters that, when reversed, would result in the exact same sequence of characters.

Take the word ‘rotator’ for example – when spelt backwards, you still get the word ‘rotator’. Hence, it’s a palindrome!  

Palindromes can be found in words or numbers. Below, we have discussed different ways in which you can check whether a string is a palindrome or not.

Methods to Check if a String is a Palindrome 

Method 1 – Using the reverse and compare method 

So, for this method, as described above, we are going to find the reversed string and then compare it with the original string. If the strings match, it’s a palindrome. It’s as simple as it sounds!  


 
#Define a function
def isPalindrome(string):
    if(string == string[::-1]):
        return"The string is a palindrome."
    else:
        return"The string is not a palindrome."
#Enter input string
string =input("Enter string: ")
print(isPalindrome(string))
Copy code
2022_06_image-149.jpg

 

 

 

Let’s look at the output when we enter the string “rodent” : 

2022_06_image-152.jpg

 

Read More: How to check if the given string is a Palindrome in Java?

From nerd to expert ninja! Unlock Python on a deeper level and explore the best Python programmes from top colleges and online Python courses with our detailed guide.

What have we done here?  

  • In the above code, we start by declaring the isPalindrome() function and passing the string argument.  
  • Then, in the function body, we get the reverse of the input string using a slice operator – string[::-1]. Here, -1 is the step parameter that ensures that the slicing will start from the end of the string with one step back each time. 
  • Now, if the reversed string matches the input string, it is a palindrome 
  • Or else, it is not a palindrome. 

Method 2 – Using for loop 

In this method, we will use the for loop to iterate each character in the given string to join it with each element stored in an empty variable declared by us. Let’s see how this is done: 


 
#Enter input string
string =input("Enter string : ")
#Declare an empty string variable 
revstr =""
#Iterate string with for loop
for i in string:
    revstr = i + revstr  
print("Reversed string : ", revstr)
if(string == revstr):
   print("The string is a palindrome.")
else:
   print("The string is not a palindrome.")
Copy code
2022_06_image-153.jpg

 

 

 

What have we done here?  

  • In the above code, we enter an input string. 
  • Then, we declare an empty string variable revstr that will store the reversed string. 
  • Next, we use the for loop to iterate all characters of the input string to concatenate each element stored in the revstr variable. 
  • Once the for loop has completed execution, we use the if-else loop to check  
  • Whether the reversed string matches the input string, i.e., a palindrome. Otherwise, not a palindrome. 

Method 3 – Using a while loop 

A while loop is often a preferred choice over the for loop method because the string does not need to be reassigned during loop execution, and hence, the program won’t consume much memory for larger strings. Let’s see how while loops are used to find a palindrome:


 
#Define a function
def isPalindrome(string):
    string = string.lower().replace(' ','')
    first, last =0,len(string)-1
    while(first < last):
        if(string[first]== string[last]):
            first +=1
            last -=1
        else:
            return"The string is not a palindrome."
    
    return"The string is a palindrome."
#Enter input string
str1 =input("Enter string : ")
print(isPalindrome(str1))#Returns True
Copy code
2022_06_image-154.jpg

What have we done here?  

  • In the above code, we start by declaring the isPalindrome() function and passing the string argument.  
  • Then, we define two variables first and last and assign them with values 0 and len(string) -1, respectively. In the above code, we enter an input string. 
  • Next, we use the while loop to iterate all characters of the input string from start to end. The loop will evaluate whether or not the nth index value from the front matches the nth index value from the back. If True, the function returns that the string is a palindrome.  
  • If the first and last characters don’t match, the loop breaks immediately and does not check the entire string (unlike the for loop). 

Method 4 – Using the reverse and join method 

In this case, we will use the in-built reversed() method to cycle through the characters of the string in reverse order. Then, we will match the reversed string with the input string to check if it is a palindrome.  

This is similar to Method 1; however, we will use the join() method instead of the slicing operator in this method. Let’s see how: 


 
#Define a function
def isPalindrome(string):
    revstr=''.join(reversed(string))
    if string==revstr:
         return"The string is a palindrome."
    return"The string is not a palindrome."
#Enter input string
string =input("Enter string: ")
print(isPalindrome(string))
Copy code
2022_06_image-156.jpg

What have we done here?  

  • In the above code, we first declare the isPalindrome() function and pass the string argument.  
  • In the function body, we then pass the input string using the reversed() function to iterate the characters of the string in reverse.  
  • The reversed characters are then joined by applying the join() function and stored in the revstr variable.  
  • We then use the if loop to check whether the reversed string matches the input string, i.e., a palindrome. Otherwise, not a palindrome. 

Method 5 – Using an iterative loop 


 
#Define a function
def isPalindrome(string):
    for i inrange(int(len(string)/2)):
        if string[i]!= string[len(string)-i-1]:
            return"The string is not a palindrome."
    return"The string is a palindrome."
#Enter input string
string =input("Enter string: ")
print(isPalindrome(string))
Copy code
2022_06_image-157.jpg

What have we done here?  

  • In the above code, we have declared the isPalindrome() function and passed the string argument to it.  
  • Then, in the function body, we run a for loop from range 0 to the middle of the input string. 
  • During the for loop execution, we check whether the nth index value from the front matches the nth index value from the back.  
  • Now, if it DOES NOT match, the string is NOT a palindrome. 
  • Otherwise, the string is a palindrome. 

Method 6 – Using recursion 

In this method, we reverse a string using the recursion method which is a process where the function calls itself. Then we check if the reversed string matches with the original string, just like we did in the previous examples. 


 
#Define a function
def isPalindrome(string):
    iflen(string)<1:
        returnTrue
    else:
        if string[0]== string[-1]:
            return isPalindrome(string[1:-1])
        else:
            returnFalse
#Enter input string
str1 =input("Enter string : ")
if(isPalindrome(str1)==True):
   print("The string is a palindrome.")
else:
   print("The string is not a palindrome.")
Copy code
2022_06_image-158.jpg

What have we done here?  

  • In the above code, we have again declared the isPalindrome() function and passed the string argument to it.  
  • Then, in the function body, we define the base condition of recursion using nested if-else loops –  
  • Now, if the length of a string < 1, return True.  
  • Or else, if the last character of the string matches the first character, the function is called recursively with the argument as the sliced string having the first and last characters removed, else return False. 
  • Then we finally use an if statement to check whether the returned value is True or False and print the output as shown. 

Endnotes 

I hope this article will be helpful for you to understand the different ways in which one can check if a Python string is a palindrome or not.
Keep Learning!!
Keep Sharing!!

Why Learn Python? Reasons and Top Resources to Learn Python
Why Learn Python? Reasons and Top Resources to Learn Python
Python is an object-oriented programming language that is used everywhere from back-end web servers to front-end development and everything in between. Its high-level built-in data structures mixed with data binding...read more
Python vs R for Data Science – A Comparative Analysis
Python vs Java: Which is Better to Learn in 2024?
Python vs Java: Which is Better to Learn in 2024?
In the world of programming, Python and Java have long been two of the most popular languages. Both have their strengths and are suited to different tasks, but recent trends...read more
Top 110+ Python Interview Questions and Answers
Top 110+ Python Interview Questions and Answers
Python is a widely-used general-purpose, object-oriented, high-level programming language. It is used to create web applications, and develop websites and GUI applications. The popularity of the language is due to...read more
Python While Loop Explained With Examples
Python While Loop Explained With Examples
The while loop repeatedly executes a block of statements as long as the condition evaluates to True. Flow control is a very important feature in any programming language. The real...read more
Python Data Types
Python Data Types
You want to store a value, but that value can be anything. It can be a number, list of number, strings, etc. So these different type of values are stored...read more
Getting started with Python Strings
Getting started with Python Strings
Python strings are immutable, i.e., you cannot modify the contents of the object. In this article, we will briefly discuss how to create, assign string to a variable, how to...read more
Python Lists Practice Programs For Beginners
Python Lists Practice Programs For Beginners
Test your Python Lists knowledge with practice programs! In this blog, we will solve 12 python lists exercises for beginners.
Introduction to Python Dictionary (With Examples)
Introduction to Python Dictionary (With Examples)
In this tutorial, you will learn all about Dictionary in Python: creating dictionaries, accessing dictionary items, looping through a dictionary, and other dictionary operations with the help of examples.
Understanding Python Sets (With Examples)
Understanding Python Sets (With Examples)
In this article, you will discuss about Python Sets: creating sets, accessing, adding, and removing set items, looping through a set, and other set operations with the help of examples.
Understanding Tuples in Python
Understanding Tuples in Python
In this guide, you will learn all about Tuples in Python: creating tuples, accessing tuple items, looping through a tuple, and other tuple operations with the help of examples.
Python Strings Practice Programs For Beginners
Python Strings Practice Programs For Beginners
Let us now look at some common Python practice programs based on strings that will help you master your foundations. I suggest you try to code...read more
Slicing in Python
How to Check if a Python String is a Palindrome
How to Check if a Python String is a Palindrome
A palindrome is a sequence of the word, phrases, or numbers that read the same backward as forward. In this article, we will discuss different methods how to check if...read more
How to Reverse a String in Python
How to Reverse a String in Python
In Python programming, strings are a sequence of characters or symbols. As a beginner practicing Python string operations, you will often come across problems that need you to work with...read more
Methods to Check for Prime Numbers in Python
Methods to Check for Prime Numbers in Python
Prime numbers are the building blocks of mathematics, and they have fascinated mathematicians for centuries. Regarding Python programming, there are different methods to check whether the given number is a...read more
Handling missing values: Beginners Tutorial
Handling missing values: Beginners Tutorial
We take data from sometimes sources like kaggle.com, sometimes we collect from different sources by doing web scrapping containing missing values in it. But do you think 
How to Convert a Python List to String?
How to Convert a Python List to String?
In Python, converting a list to a string is a common operation in order to make it convenient to perform data manipulation. In this article, we will briefly discuss the...read more
How to Convert Celsius to Fahrenheit in Python
How to Convert Celsius to Fahrenheit in Python
One of the most common Python programs for beginners is to convert temperature from Celsius to Fahrenheit and vice versa. This tutorial will help you learn how to perform both...read more

FAQs on How to Check if a Python String is a Palindrome

What is a Palindrome?

A palindrome is a word, phrase, number, or sequence of characters that reads the same forward or backward. Common examples include "racecar", "level", and "madam".

What is the most famous Palindrome?

Some of the most famous palindromes are, MADAM, ROTATOR, REFER, LEVEL etc.

What is the 5 letter pallindrome?

RADAR, LEVEL, CIVIC, MADAM, REFER are some famous 5 letter palindrome.

How many seven-letter palindrome are possible?

For a 7-letter palindrome, the word structure would look like this: ABCDCBA. This means that you only have to choose the first 4 letters, and the last 3 letters are determined by your choices for the first 3. So, the total number of 7-letter palindromes possible is 26 x 26 x 26 x 26 = 4,56,976.

Are there built-in methods in Python to check for palindromes?

Python doesn't have a built-in function specifically for checking palindromes, but you can use Python's string slicing and other built-in functions to create efficient palindrome-checking methods.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio

Comments