How to check if a string is palindrome in python / Various methods to check for a palindrome string in python / How to reverse a string in python

What is a palindrome string
A string whose characters if arranged backwards(or in reverse order) are the same as the original string is called Palindrome. Examples of palindrome string are dad, kayak, rotor, malayalam etc.
There are many methods to test a string to be palindrome and all the approaches require the string to be reversed and then comparing this reversed string with the actual string. If they both match, the string will be palindrome. This post will cover all such methods. Read on!!!

Method 1: Using string slicing
Reverse a string using python’s string slicing operator and compare the reversed string to the original string. If both are equal, then string is palindrome else not. Example,

# read string from keyboard
original_string = input("Enter a string\n")
# reverse the string
reversed_string = original_string[::-1]
# compare original and reversed string
if(original_string == reversed_string):
    print("String is palindrome")
else:
    print("String is not palindrome")

String slicing operator with double colon(::) accepts numeric arguments on both sides of the colon. First numeric argument represents the start index, second represents the end index and third represents the number of characters to skip while slicing.

If the first numeric argument is omitted, it is assumed to be 0(means the start of string). Negative index means start from right end.
If the second numeric argument is omitted, it is assumed to be length of string – 1(means the end of string).
If the third numeric argument is omitted, it is assumed to be 1(no skipping). If it is negative, this means that string slicing will be done from right to left direction.

From left to right
Index of first character from left of the string is 0 and index of last character of the string from left is length of string -1.
From right to left
Index of first character from of the string is -1 and index of last character of the string is (-length of string -1).

Thus, for a sample string “codippa the website“, following table will make you understand it better.

Pattern Result Explanation
str[1:10:1] or str[1:10:] odippa th Start from index 1 till 9 with an interval of 1 character
str[1:10:2] oip h Start from index 1 till 9 with an interval of 2 characters
str[:10:1] codippa th Start from index 0 till 9 with an interval of 1 character
str[1::1] odippa the website Start from index 1 till end with an interval of 1 character
str[:-1:1] or str[:-1:] codippa the websit Start from index 0 till second last character with an interval of 1 character
str[-1:-10:-1] or str[:-10:-1] etisbew e Start from last character from right till the 9th character with an interval of 1 character
str[-2:-10:-1] tisbew e Start from second last character from right till the 9th character with an interval of 1 character

Thus, ::-1 means start from the right end of the string till the left end with an interval of 1 character. It can also be written as -1::-1.
Sample runs of the above program are

Enter a string
codippa
String is not palindrome

Enter a string
rotor
String is palindrome

Method 2: Using reversed function
Python provides a reversed function which takes an object and returns an iterator over that object but in reverse order. The object expected by reversed function can be a list, a tuple, a string etc. When reversed function is supplied a string it returns an iterator which if iterated will return the characters of the string.
Python docs of reversed function state

reversed(sequence)
Returns a reverse iterator over values of the sequence

This iterator is then supplied to join function which combines the values in the supplied iterator with the string on which it is called. Since we want to join the values(or characters) in the iterator with an empty string, we call join on an empty string. This will return the reversed string. This reversed string is compared with the original string to determine if it is palindrome or not.


Python docs of join function state

S.join(iterable) -> str
Return a string which is the concatenation of the strings in the iterable. The separator between elements is S.

# read string from keyboard
original_string = input("Enter a string\n")
# reverse the string by joining the characters with an empty string
reversed_string = ''.join(reversed(original_string))
# compare original and reversed string
if(original_string == reversed_string):
    print("String is palindrome")
else:
    print("String is not palindrome")

Sample runs of the above program are

Enter a string
kayak
String is palindrome

Enter a string
python
String is not palindrome

Method 3: Using recursive method
A recursive method calls itself. There should be some condition in this method which should cause it to return else it will keep on calling itself and will be stuck in an infinite loop.
Below code contains a recursive function which accepts a string as an argument and checks if it palindrome or not. First it checks whether the length of the string is 0. If it is 0 means the string is palindrome since 0 length strings are considered to be palindrome.


Next, it compares the first and last characters of the string. If they match, it calls itself supplying it the string with first and last characters removed. Again, it repeats the same set of steps with the first and last characters of remaining string removed. This way all the characters of the string are compared.
If the first and last characters during any invocation of this function do not match, then the function returns False.

# recursive function to check if string is palindrome or not
def isPalindrome(str):
    # zreo length strings are palindrome, hence return True
    if len(str) ==0:
        return True
    # check if first and last character of string match
    if str[0] == str[-1]:
        # call itself with first and last characters removed
        return isPalindrome(str[1:-1])
    # return if first and last characters do not match
    return False
 
# read string from keyboard
original_string = input("Enter a string\n")
# call palindrome function
palindrome = isPalindrome(original_string)
if(palindrome == True):
    print("String is palindrome")
else:
    print("String is not palindrome")

Following are the sample runs of above program

Enter a string
parrot
String is not palindrome

Enter a string
erre
String is palindrome

Method 4: Using iterative approach
Initialize a variable(say A) equal to the length of the string or the number of characters in it. Subtract 1 from this variable so that it points to the last character(since index of characters of string start from 0 till 1 less than length of the string).


Iterate over the characters of the string starting from left to right. In every iteration compare the character at current loop count position and character at corresponding right end using the variable(A) initialized above.
If they both match, then continue with next iteration and decrease the value of variable(A) by 1 so that each character from the left end is compared with the corresponding character at the right end.
Continue iteration till any two characters do not match or value of variable(A) becomes lesser than the current loop count which means that all characters have been compared. Code follows

# iterative function to check if string is palindrome or not
def isPalindrome(str):
    # get index of last character of string
    endIndex = len(str) - 1
    # iterate over string
    for index in range(len(str)):
        # check if whole string has been checked
        if endIndex < index:
            return True
        # compare left and right characters 
        if str[index] == str[endIndex]:
            endIndex = endIndex - 1
        else:
        # characters don't match, string is not palindrome
            return False
 
# read string from keyboard
original_string = input("Enter a string\n")
# call palindrome function
palindrome = isPalindrome(original_string)
if(palindrome == True):
    print("String is palindrome")
else:
    print("String is not palindrome")

Sample runs of the above program produce following output

Enter a string
rabbit
String is not palindrome

Enter a string
dad
String is palindrome

If you are familiar with any other approaches to check for a palindrome string, do not forget to comment. Keep visiting!!!

0

Mark Your Impression

Close Menu