Skip to content

Python Program to Check If a String is a Palindrome (6 Methods)

Python Program to Check If a String is a Palindrome (6 Methods) Cover Image

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:

What is a palindrome?

A palindrome is a word, phrase, or sequence that is the same spelled forward as it is backward.

The Quick Answer: Use String Indexing

https://e6v4p8w2.rocketcdn.me/wp-content/uploads/2021/09/Quick-Answer-Python-Check-if-a-String-is-a-Palindrome-1024x544.png
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

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:

  1. We define a function, palindrome(), that takes a single string as its only parameter
  2. 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)
  3. We then evaluate whether or not the modified string is equal to the modified string in reverse order
  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.

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:

  1. Similar to the method above, the function first changes all casing to lower case and removes all spaces
  2. Then, it uses the reverse() function to reverse the string.
  3. Because the reverse() function returns a reversed object, we need to turn it back into a string. This can be done using the .join() method.
  4. 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:

  1. We define a function, palindrome(), which accepts a string as its only argument
  2. We format our string in all lowercase and replace any spaces
  3. We then create two variables, first and last which are equal to 0 and the length of the list minus 1, respectively
  4. We then create a while loop, which runs as long as the value of first is less than last
  5. The loop evaluates if the indexed value of first and last are equal to one another
  6. If they are, the values are incremented and decremented by 1, respectively
  7. 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
    else:
        return palindrome(a_string[1:-1])


print(palindrome(a_string))

# Returns:
# True

Let’s break down what we did in the code above:

  1. We defined a function, palindrome(), which takes a string as its only parameter
  2. The function first lowercases the string and removes any spaces
  3. Then, it checks if the first and last characters are the same
  4. If they are not, then the function returns False
  5. 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.

What is the fastest way to use Python to check if a string is a palindrome?

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:

MethodExecution Time (10,000,000 characters)
String indexing22.7 ms
reversed() Function303 ms
While Loop1.02 s
For Loop1.6 s

The image below breaks down the speed comparison:

Fastest Method to Use Python to Check if a String is a Palindrome
Using string slicing is the fastest way to check if a string is a palindrome in Python

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:

2 thoughts on “Python Program to Check If a String is a Palindrome (6 Methods)”

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

Leave a Reply

Your email address will not be published.