0% found this document useful (0 votes)
2 views15 pages

How to Check if a Python String is a Palindrome

The document discusses how to check if a Python string is a palindrome, which is a sequence that reads the same backward as forward. It outlines several methods to determine if a string is a palindrome, including using reverse comparison, for loops, while loops, and recursion. Each method is explained with sample code to illustrate how to implement the palindrome check in Python.

Uploaded by

shailenderojha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views15 pages

How to Check if a Python String is a Palindrome

The document discusses how to check if a Python string is a palindrome, which is a sequence that reads the same backward as forward. It outlines several methods to determine if a string is a palindrome, including using reverse comparison, for loops, while loops, and recursion. Each method is explained with sample code to illustrate how to implement the palindrome check in Python.

Uploaded by

shailenderojha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

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.

We will be covering the following sections today:


What is a Palindrome?

Methods to Check if a String is a Palindrome

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!

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

Met hod 1 – Using t he reverse and compare met hod

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."

#Enter input string


st ring = input ("Ent er st ring: ")

print (isPalindrome(st ring))

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” :

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() 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.

Now, if the reversed string matches the input string, it is a palindrome

Or else, it is not a palindrome.

Met hod 2 – Using f or loop

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

#Enter input string


st ring = input ("Ent er st ring : ")

#Declare an empty string variable


revst r = ""

#Iterate string with for loop


f or i in st ring:
revst r = i + revst r
print ("Reversed st ring : ", revst r)

if (st ring == revst r):


print ("T he st ring is a palindrome.")
else:
print ("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.
What have we done here?

In the above code, we enter an input string.

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.

Met hod 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:

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."

ret urn "T he st ring is a palindrome."

#Enter input string


st r1 = input ("Ent er st ring : ")

print (isPalindrome(st r1)) #Returns True

What have we done here?

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).

Met hod 4 – Using t he reverse and join met hod

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."

#Enter input string


st ring = input ("Ent er st ring: ")

print (isPalindrome(st ring))

What have we done here?

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.

Met hod 5 – Using an it erat ive loop

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."

#Enter input string


st ring = input ("Ent er st ring: ")

print (isPalindrome(st ring))

What have we done here?

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.

Now, if it DOES NOT match, the string is NOT a palindrome.

Otherwise, the string is a palindrome.

Met hod 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.

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

#Enter input string


st r1 = input ("Ent er st ring : ")

if (isPalindrome(st r1)==T rue):


print ("T he st ring is a palindrome.")
else:
print ("T he st ring is not a palindrome.")

What have we done here?

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 –

Now, if the length of a string < 1, return T rue.

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!!

Why Learn Pyt hon? Reasons and Top Resources t o Lea…


Pyt hon
Pytho n is an o bject-o riented pro gramming language that is used everywhere
fro m back-end web servers to fro nt-end develo pment and everything in between. Its high-level built-in data
structures mixed with data binding...re ad m o re

Python vs R f or Data Science – A Comparative


Analysis

With the massive growth in the importance of big data, machine


learning, and data science across the industries, two languages emerged
as the most f avorable...read more

Pyt hon vs Java: Which is Bet t er t o Learn in 2024?


In the wo rld o f pro gramming, Pytho n and Java have lo ng been two o f the mo st
po pular languages. Bo th have their strengths and are suited to different tasks,
but recent trends...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.
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

Pyt hon While Loop Explained Wit h Examples


The while lo o p repeatedly executes a blo ck o f statements as lo ng as the
co nditio n evaluates to True. Flo w co ntro l is a very impo rtant feature in any
pro gramming language. The real...re ad m o re

Pyt hon Dat a Types


Yo u want to sto re a value, but that value can be anything. It can be a number, list
o f number, strings, etc. So these different type o f values are sto red...re ad m o re

Get t ing st art ed wit h Pyt hon St rings


Pytho n strings are immutable, i.e., yo u canno t mo dify the co ntents o f the o bject.
In this article, we will briefly discuss ho w to create, assign string to a variable,
ho w to ...re ad m o re

Pyt hon List s Pract ice Programs For Beginners


Test yo ur Pytho n Lists kno wledge with practice pro grams! In this blo g, we will
so lve 12 pytho n lists exercises fo r beginners.

Int roduct ion t o Pyt hon Dict ionary (Wit h Examples)


In this tuto rial, yo u will learn all abo ut Dictio nary in Pytho n: creating dictio naries,
accessing dictio nary items, lo o ping thro ugh a dictio nary, and o ther dictio nary
o peratio ns with the help o f 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.
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.

Underst anding Tuples in Pyt hon


In this guide, yo u will learn all abo ut Tuples in Pytho n: creating tuples, accessing
tuple items, lo o ping thro ugh a tuple, and o ther tuple o peratio ns with the help o f
examples.

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 f oundations. I
suggest you try to code...read more

Slicing in Python

Strings are ordered collections of characters, which


is why you can access the items (or characters) of the string based on
their position. This we ref er...read more

How t o Check if a Pyt hon St ring is a Palindrome


A palindro me is a sequence o f the wo rd, phrases, o r numbers that read the
same backward as fo rward. In this article, we will discuss different metho ds ho w
to check if...re ad m o re

How t o Reverse a St ring in Pyt hon


In Pytho n pro gramming, strings are a sequence o f characters o r symbo ls. As a
beginner practicing Pytho n string o peratio ns, yo u will o ften co me acro ss
pro blems that need yo u to wo rk with...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.
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

Handling missing values: Beginners Tut orial


We take data fro m so metimes so urces like kaggle .co m , so metimes we co llect
fro m different so urces by do ing web scrapping co ntaining m issing value s in it.
But do yo u think

How t o Convert a Pyt hon List t o St ring?


In Pytho n, co nverting a list to a string is a co mmo n o peratio n in o rder to make it
co nvenient to perfo rm data manipulatio n. In this article, we will briefly discuss
the...re ad m o re

How t o Convert Celsius t o Fahrenheit in Pyt hon


One o f the mo st co mmo n Pytho n pro grams fo r beginners is to co nvert
temperature fro m Celsius to Fahrenheit and vice versa. This tuto rial will help yo u
learn ho w to perfo rm bo th...re ad m o re

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

What is a Palindrome?

What is the most f amous Palindrome?

What is the 5 letter pallindrome?

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?

Are there built-in methods in Python to check f or palindromes?

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.

You might also like