One of the most popular simple coding questions to solve is to check whether a string is a palindrome or not.

Table of contents


Introduction

What is a palindrome? A palindrome is a word (or a sequence of characters) which reads the same backward and forward.

Here are a few examples: racecar, level, kayak, civic, and more.

Writing a quick script to check whether a string is a palindrome or not is still a popular question for some entry level jobs in the field of data science to check the candidates logic. It is particularly interesting because there are multiple ways of solving this challenge.


Method 1: Slicing

This is one of the quickest ways to solve this challenge. It requires reverse a string using the slicing method [::-1]:


def palindrome(word):
    rword = word[::-1]
    if word == rword:
        return True
    else:
        return False

What this function does is it simply reverses the string character by character. Let’s see if it solves our challenge:


palindrome("civic")

The output we get is: True

Now checking a word that’s not a palindrome:


palindrome("sample")

The output we get is: False


Method 2: Iterative Approach

This way of solving the palindrome challenge is also great to showcase during the interview. It is a more standardize programmatic approach.


def palindrome(word):
    d = range(int(len(word)/2))
    for i in d:
        if word[i] != word[-i-1]:
            return False
            break
    return True

So how are we going to do it?

First, we will find the distance to the middle of the string and store is as d. For example, if the word is “civic”, the distance to the middle is 2.5 characters (note: we take into account strings with even and odd number of characters by taking only the integer only of the half of the length). So in the above case, d = 2.

Then, knowing the “distance” value, we iterate through the numbers between 0 and d and compare it with the character at the other end of the string. In case of the word “civic”, we start with comparing first character and last character, both are “c”, so we continue. Then second character with second last character, both are “i”. At this point loop ends, and if there were no mismatches, the function returns True.

Let’s see if it solves our challenge:


palindrome("civic")

The output we get is: True


palindrome("sample")

The output we get is: False


Conclusion

In this article we explored how to solve the palindrome challenge in Python using two most common approaches.

Of course, there are several more ways of checking is a string is a palindrome in Python and if you come up with something interesting and/or creative, I’d be very interested to take a look.