Python: Check If a String is a Palindrome (5 Easy Ways!)

Python Check if a String is a Palindrome Cover Image

In this tutorial, you’ll learn how to use Python to check if a string is a palindrome. You’ll learn 5 different ways, 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: what is a palindrome? A palindrome is a word, phrase, or sequence that is the same spelled forward as it is backwards.

The Quick Answer: Use String Indexing

Quick Answer - Python Check if a String is a Palindrome
Quick Answer – Python Check if a String is a Palindrome using String Indexing

Use Python String Indexing to Check if a String is a Palindrome

One of the easiest ways to use Python to check if a string is a palindrome is to use string indexing.

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 a 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(string):
    string = string.lower().replace(' ', '')
    return string == string[::-1]

print(palindrome(a_string))

# Returns: True

Let’s explore what we’ve done here:

  1. We define a function that takes a single string
  2. We then re-assign the string to itself, but lower all the character cases and remove any spaces
  3. We then return the evaluation of whether the string is equal to itself, backwards
  4. This returns True if the string is a palindrome, and False 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.

Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

Use the Python Reversed Function to Check if a String is a Palindrome

Python comes with a built-in function, reversed(), which, well, reverses an item. 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(string):
    string = string.lower().replace(' ', '')
    reversed_string = ''.join(reversed(string))
    return string == reversed_string

print(palindrome(a_string))

# Returns: True

Let’s take a look at what our function does:

  1. Similar to the method above, it first changes all casing to lower case and removes all spaces
  2. Then, it uses the reverse() function to reverse the string. This is then joined.
  3. Finally, the two strings are evaluated against whether or not they’re equal.

Now, you might be wondering why we need to use the ''.join() method. The reversed() function actually returns a reversed object type, which isn’t a string, but more similar to a built-in list.

In the next section, you’ll learn how to use a for loop to check if a string is a palindrome.

Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.

Using a For Loop to Check if a Python String is a Palindrome

Similar to the above methods, we can use a Python for-loop to loop over a string through the reverse to see if its characters match.

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(string):
    string = string.lower().replace(' ', '')
    reversed = ''
    for i in range(len(string), 0, -1):
        reversed += string[i-1]
    return string == reversed

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.

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

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(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 False
    
    return True

print(palindrome(a_string))

# Returns: True

What we do here is loop over the string from beginning to end. Our while loop evaluates whether or not the ith index from the front is equal to the ith index from the back.

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.

In the next section, you’ll learn how to check whether or not a number is a palindrome.

Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.

Check if a Number is a Python Palindrome

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 the next section, you’ll learn how to find a palindrome in a larger string.

Want to find the index of a substring (or all substrings) in a Python string? Check out this tutorial here to learn how to!

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.

Need to remove the first characters from a string in Python? This tutorial will teach you a number of different and easy ways to do this.

To learn more about the reversed() function, check out the official documentation here.