How to Check if a Python String is a Palindrome
How to Check if a Python String is a Palindrome
Shiksha Online
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.
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.
But first, for the unaware, let’s talk about what a palindrome really is, shall we?
What is a Palindrome?
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
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!
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!
Copy code
#Define a function
def isPalindrome(st ring):
if (st ring == st ring[::-1]) :
ret urn "T he st ring is a palindrome."
else:
ret urn "T he st ring is not a palindrome."
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
Let’s look at the output when we enter the string “rodent” :
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.
In the above code, we start by declaring the isPalindrome() f unction and passing the
string argument.
T hen, in the f unction 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 f rom the
end of the string with one step back each time.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
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:
Copy code
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
What have we done here?
T hen, we declare an empty string variable revstr that will store the reversed string.
Next, we use the f or loop to iterate all characters of the input string to concatenate each
element stored in the revstr variable.
Once the f or 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.
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:
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
Copy code
#Define a function
def isPalindrome(st ring):
st ring = st ring.lower().replace(' ', '')
f irst , last = 0, len(st ring) - 1
while(f irst < last ):
if (st ring[f irst ] == st ring[last ]):
f irst += 1
last -= 1
else:
ret urn "T he st ring is not a palindrome."
In the above code, we start by declaring the isPalindrome() f unction and passing the
string argument.
T hen, we def ine 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 f rom start to end.
T he loop will evaluate whether or not the nth index value f rom the f ront matches the nth
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
index value f rom the back. If T rue, the f unction returns that the string is a palindrome.
If the f irst and last characters don’t match, the loop breaks immediately and does not
check the entire string (unlike the f or loop).
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:
Copy code
#Define a function
def isPalindrome(st ring):
revst r=''.join(reversed(st ring))
if st ring==revst r:
ret urn "T he st ring is a palindrome."
ret urn "T he st ring is not a palindrome."
In the above code, we f irst declare the isPalindrome() f unction and pass the string
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
argument.
In the f unction body, we then pass the input string using the reversed() f unction to iterate
the characters of the string in reverse.
T he reversed characters are then joined by applying the join() f unction 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.
Copy code
#Define a function
def isPalindrome(st ring):
f or i in range(int (len(st ring)/2)):
if st ring[i] != st ring[len(st ring)-i-1]:
ret urn "T he st ring is not a palindrome."
ret urn "T he st ring is a palindrome."
In the above code, we have declared the isPalindrome() f unction and passed the string
argument to it.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
T hen, in the f unction body, we run a f or loop f rom range 0 to the middle of the input
string.
During the f or loop execution, we check whether the nth index value f rom the f ront
matches the nth index value f rom the back.
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.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
Copy code
#Define a function
def isPalindrome(st ring):
if len(st ring) < 1:
ret urn T rue
else:
if st ring[0] == st ring[-1]:
ret urn isPalindrome(st ring[1:-1])
else:
ret urn False
In the above code, we have again declared the isPalindrome() f unction and passed the
string argument to it.
T hen, in the f unction body, we def ine the base condition of recursion using nested if -else
loops –
Or else, if the last character of the string matches the f irst character, the f unction is
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
called recursively with the argument as the sliced string having the f irst and last characters
removed, else return False.
T hen we f inally use an if statement to check whether the returned value is T rue 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!!
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
Top 110+ Pyt hon Int erview Quest ions and Answers
Pytho n is a widely-used general-purpo se, o bject-o riented, high-level
pro gramming language. It is used to create web applicatio ns, and develo p
websites and GUI applicatio ns. The po pularity o f the language is due to ...re ad
m o re
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
Underst anding Pyt hon Set s (Wit h Examples)
In this article, yo u will discuss abo ut Pytho n Sets: creating sets, accessing,
adding, and remo ving set items, lo o ping thro ugh a set, and o ther set o peratio ns
with the help o f examples.
Slicing in Python
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
Met hods t o Check f or Prime Numbers in Pyt hon
Prime numbers are the building blo cks o f mathematics, and they have
fascinated mathematicians fo r centuries. Regarding Pytho n pro gramming, there
are different metho ds to check whether the given number is a...re ad m o re
What is a Palindrome?
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
How many seven-letter palindrome are possible?
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.