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 of checking if a string is a palindrome in Python or not.
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.
Best-suited Python courses for you
Learn Python with these high-rated online courses
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))
Let’s look at the output when we enter the string “rodent” :
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.")
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
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))
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 in range(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))
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): if len(string) < 1: return True else: if string[0] == string[-1]: return isPalindrome(string[1:-1]) else: return False #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.")
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!!
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.
Vikram has a Postgraduate degree in Applied Mathematics, with a keen interest in Data Science and Machine Learning. He has experience of 2+ years in content creation in Mathematics, Statistics, Data Science, and Mac... Read Full Bio