In this tutorial, you’ll learn how to use Python to check if a string is a palindrome. You’ll learn six different ways to check if a string is a palindrome, including using string indexing, for loops, the reversed()
function.
You’ll also learn the limitations of the different approaches, and when one might be better to use than another. But before we dive in, let’s answer a quick question:
A palindrome is a word, phrase, or sequence that is the same spelled forward as it is backward.
The Quick Answer: Use String Indexing
Table of Contents
Use Python String Indexing to Check if a String is a Palindrome
String indexing provides the simplest way in Python to check if a string is a palindrome. String indexing can be used to iterate over a string in reverse order.
One of the greatest things about Python indexing is that you can set a step counter as well, meaning you can move over an iterable at the desired rate. The way that we’ll make use of this is to use a step of -1
, meaning that we move over the iterable from the back to the front.
An important thing to keep in mind is that your string may have different casing as well as spaces. Because of this, we’ll need to preprocess our string to remove capitalization and any spaces.
Let’s take a look at using string indexing to check if a string is a palindrome in Python:
# Use String Indexing in Python to check if a String is a Palindrome
a_string = 'Was it a car or a cat I saw'
def palindrome(a_string):
a_string = a_string.lower().replace(' ', '')
return a_string == a_string[::-1]
print(palindrome(a_string))
# Returns: True
Let’s explore what we’ve done in the code above:
- We define a function, palindrome(), that takes a single string as its only parameter
- We then re-assign the string to itself but lower all the character cases (using the
.lower()
method) and remove any spaces (using the.replace()
method) - We then evaluate whether or not the modified string is equal to the modified string in reverse order
- This returns
True
if the string is a palindrome, andFalse
if it is not
Now, let’s take a look at how we can use the Python reversed()
function to check if a string is a palindrome.
Use the Python Reversed Function to Check if a String is a Palindrome
Python comes with a built-in function, reversed()
, which reverses an iterable item, such as a string. You can pass in some iterable item, be it a string, a list, or anything else ordered, and the function returns the reversed version of it.
Let’s take a look at how we can use the reversed()
function:
# Use the Reversed() function in Python to check if a String is a Palindrome
a_string = 'Was it a car or a cat I saw'
def palindrome(a_string):
a_string = a_string.lower().replace(' ', '')
reversed_string = ''.join(reversed(a_string))
return a_string == reversed_string
print(palindrome(a_string))
# Returns: True
Let’s take a look at what our function does:
- Similar to the method above, the function first changes all casing to lower case and removes all spaces
- Then, it uses the
reverse()
function to reverse the string. - Because the
reverse()
function returns areversed
object, we need to turn it back into a string. This can be done using the.join()
method. - Finally, the two strings are evaluated against whether or not they’re equal.
In the next section, you’ll learn how to use a for loop to check if a string is a palindrome.
Using a For Loop to Check if a Python String is a Palindrome
You can also use a Python for-loop to loop over a string in reverse order, to see if a string is a palindrome or not.
Let’s see how we can use a for loop to check if a string is a palindrome:
# Use a For Loop in Python to check if a String is a Palindrome
a_string = 'Was it a car or a cat I saw'
def palindrome(a_string):
a_string = a_string.lower().replace(' ', '')
reversed_string = ''
for i in range(len(a_string), 0, -1):
reversed_string += a_string[i-1]
return a_string == reversed_string
print(palindrome(a_string))
# Returns: True
What we’ve done here is traversed the list from the last index, -1
, to its first, 0
. We then assign that value to a string reversed
. Finally, we evaluate whether the two strings are equal.
In the next section, you’ll learn how to use a Python while loop to see if a palindrome exists.
Using a Python While Loop to Check if a String is a Palindrome
In this section, let’s explore how to use a Python while loop to see if a string is a palindrome or not.
One of the benefits of this approach is that we don’t actually need to reassign a reversed string, which, if your strings are large, won’t consume much memory.
Let’s see how we can use a Python while loop:
# Use a While Loop in Python to check if a String is a Palindrome
a_string = 'Was it a car or a cat I saw'
def palindrome(a_string):
a_string = a_string.lower().replace(' ', '')
first, last = 0, len(a_string) - 1
while(first < last):
if(a_string[first] == a_string[last]):
first += 1
last -= 1
else:
return False
return True
print(palindrome(a_string))
# Returns: True
Let’s break down what the code block above is doing:
- We define a function,
palindrome()
, which accepts a string as its only argument - We format our string in all lowercase and replace any spaces
- We then create two variables,
first
andlast
which are equal to 0 and the length of the list minus 1, respectively - We then create a while loop, which runs as long as the value of
first
is less thanlast
- The loop evaluates if the indexed value of
first
andlast
are equal to one another - If they are, the values are incremented and decremented by 1, respectively
- If not, the function returns
False
A major performance benefit here can be that if a string is clearly not a palindrome, say if the first and last characters don’t match, then the loop breaks. This saves us significant memory and time.
Check if a String is a Palindrome Using Recursion in Python
In this section, you’ll learn how to use recursion to check if a string is a palindrome in Python. Recursive functions can be used to make your code simpler and cleaner while providing extensive functionality.
Let’s take a look at how we can develop a recursive function that checks whether or not a string is a palindrome:
# Using Recursion to Check if a String is a Palindrome in Python
a_string = 'Was it a car or a cat I saw'
def palindrome(a_string):
a_string = a_string.lower().replace(' ', '')
if a_string[0] != a_string[-1]:
return False
elif (len(a_string) == 1):
return True
else:
return palindrome(a_string[1:-1])
print(palindrome(a_string))
# Returns:
# True
Let’s break down what we did in the code above:
- We defined a function,
palindrome()
, which takes a string as its only parameter - The function first lowercases the string and removes any spaces
- Then, it checks if the first and last characters are the same
- If they are not, then the function returns
False
- If they are, the function is called recursively, ignoring the first and last letters
In the next section, you’ll learn how to check whether or not a number is a palindrome.
Check if a Number is a Palindrome in Python
The easiest way to check if a number is a Python palindrome is to convert the number to a string and apply any of the methods mentioned above.
Let’s see how we can do this using the string indexing method:
# Use String Indexing in Python to check if a Number is a Palindrome
a_number = 123454321
def palindrome(number):
number = str(number)
return number == number[::-1]
print(palindrome(a_number))
# Returns: True
In order to check if a number is a palindrome in Python, we converted the number to a string using the str()
method. From there, we can simply check if the resulting string is a palindrome using any of the methods above. In the code example, we used string indexing to reverse the string.
What is the Fastest Way to Check if a String is a Palindrome in Python?
In the code above, you learned six different ways to use Python to check if a string is a palindrome. At this point, you may be wondering what method to use. In many cases, you’ll want to strive for readability and speed.
In this section, we tested the speed of the different methods using a palindrome that is over ten million characters long. Because recursion is generally capped at 1,000 recursive calls, this method is not tested.
The fastest way to check if a string is a palindrome using Python is to use string indexing, which can be up to 70 times faster than using a for loop.
Below, you’ll find the results of the tests:
Method | Execution Time (10,000,000 characters) |
---|---|
String indexing | 22.7 ms |
reversed() Function | 303 ms |
While Loop | 1.02 s |
For Loop | 1.6 s |
The image below breaks down the speed comparison:
Conclusion
In this post, you learned a number of different ways to check if a Python string is a palindrome. You learned how to do this with Python string indexing, the Python reversed()
function, both for and while loops. You also learned how to check if a number is a Python palindrome and how to search a larger string for a substring that is a palindrome.
Additional Documentation
To learn more about related topics, check out the tutorials below:
- Python String Contains: Check if a String Contains a Substring
- How to Check if a String is Empty in Python
- How to Concatenate Strings in Python: A Complete Guide
- Python: Count Words in a String or File
- To learn more about the
reversed()
function, check out the official documentation here.
for palindromic phrases with punctuation (ex: “Eva, can I see bees in a cave?”), I wrote a little something.
pal = input(‘Enter phrase: ‘)
stripped = “”.join(x for x in pal if x.isalnum())
if stripped.lower() == stripped[::-1].lower():
print(f'”{pal}” is a palindrome.’)
else:
print(f'”{pal}” is not a palindrome.’)
This is great! Thanks for sharing, Ryan.
# Using Recursion to Check if a String is a Palindrome in Python
It’s throwing out of Index error , I have corrected my self with below code. Can you please correct your code if below is not accurate one?
a_string = ‘Was it a car or a cat I saw’
def palindrome(a_string):
a_string = a_string.lower().replace(‘ ‘, ”)
if a_string[0] != a_string[-1]:
return False
elif (len(a_string) == 1):
return True
else:
return palindrome(a_string[1:-1])
print(palindrome(a_string))
Thanks Ashok! I have corrected the code with your version. I appreciate it!