Palindrome in Python

Palindrome in Python

  1. What Is a Palindrome
  2. Palindrome in Python
  3. Use slice to Check if Input Is Palindrome in Python
  4. Use reverse to Check if Input Is Palindrome in Python
  5. Use a while Loop to Check if Input Is Palindrome in Python
  6. Convert to Upper Case and Compare Strings to Check if Input Is Palindrome in Python

This article will discuss palindromes and how we can determine whether a string is a palindrome or not in Python programming language. We also look into multiple programming methods to determine whether a given string is a valid palindrome sequence or not.

What Is a Palindrome

A palindrome is a word, number, phrase, or sequence of words that reads the same in either forward or backward directions. Palindromes can be character palindromes as numeric palindromes.

Examples of character or string palindrome can be civic, radar, madam, etc. There are some numeric palindromes, such as date or some timestamp.

Examples of numeric palindromes can be a date like 22-02-2022 (22022022) or any timestamp like 11:11. Note that capitalization and punctuation are ignored in palindromes.

Palindrome in Python

In C language, to identify whether a literal is palindrome or not, we need to check the literal by comparing its indexes. For this purpose, multiple for loops and while loops are used to traverse the literal from start to the end.

On the other hand, Python believes in more abstraction and minimal code statements. Therefore, many built-in functions are available for better string management and to avoid lengthy programming.

There are multiple methods to identify if a given input value is palindrome or not. We will discuss some of them here.

Use slice to Check if Input Is Palindrome in Python

We can use a string slice function to slice a given string to some part. The syntax of this method is:

slice[start:end]

This will slice a given string from the start index (inclusive) to the end index (exclusive) and return the resultant string.

There is another version of the slice in which you can also specify the step value.

slice[start:end:step]

The above code will slice a given string from the start (inclusive) to the end (exclusive) with the step amount. Consider the following code segment:

def checkPalindrome(s):
    return s == s[::-1]

var = "radar"
a = checkPalindrome(var)
if(a ==True):
    print (f"{var} is a palindrome")
else:
    print (f"{var} is not a palindrome")

In this code segment, we have created a function checkPalindrome that takes input a variable as a parameter and checks whether it is a palindrome or not. This function uses the slice function with no start and end value provided and steps of -1, which reverses the given string and is then compared to the original string.

It returns True or False based on the condition. The output of this code will be:

radar is a palindrome

Use reverse to Check if Input Is Palindrome in Python

Another method to check if it is a palindrome or not is by using the reverse function of the string. The reverse function reverses the given string and returns the reversed sequence of characters.

This is exhibited in the following code segment.

def checkPalindrome(s):
    return list(s) == list(reversed(s))

var = "madam"
a = checkPalindrome(var)
if(a ==True):
    print (f"{var} is a palindrome")
else:
    print (f"{var} is not a palindrome")

The output of this code segment will be:

madam is a palindrome

Note that the list function is used here to convert the sequence of characters into a list or, we can say, an array.

Use a while Loop to Check if Input Is Palindrome in Python

There can be numerous logic to solve this problem. We have discussed two straightaway methods to check if a given string is a palindrome or not.

We can also implement a classic palindrome method by comparing the string index-by-index. This solution is given in the following example.

def checkPalindrome(s):
    ls = list(s)
    isPalindrome = True
    while len(ls) > 0 and isPalindrome:
        if ls[0] != ls[(len(ls) - 1)]:
            isPalindrome = False
        else:
            ls.pop(0)
            if len(ls) > 0:
                ls.pop((len(ls) - 1))
    return isPalindrome

var = "civic"
a = checkPalindrome(var)
if(a ==True):
    print (f"{var} is a palindrome")
else:
    print (f"{var} is not a palindrome")

The output of this code segment will be:

civic is a palindrome

In the above code, again, we have converted the given string into a list, and then we have compared it index by index, popping indexes one by one.

Convert to Upper Case and Compare Strings to Check if Input Is Palindrome in Python

In all the above methods, we have ignored the case sensitivity of the words. As shown in the following example, we can cater to this situation by comparing the strings after converting them to upper case.

def checkPalindrome(s):
    return s.upper() == s.upper()[::-1]

var = "Civic"
a = checkPalindrome(var)
if(a ==True):
    print (f"{var} is a palindrome")
else:
    print (f"{var} is not a palindrome")

The output of this code segment will be:

Civic is a palindrome

We can see there are many ways to solve the palindrome problem in Python that are very straightforward and require significantly lesser lines of code as compared to C and C++.

Muhammad Husnain avatar Muhammad Husnain avatar

Husnain is a professional Software Engineer and a researcher who loves to learn, build, write, and teach. Having worked various jobs in the IT industry, he especially enjoys finding ways to express complex ideas in simple ways through his content. In his free time, Husnain unwinds by thinking about tech fiction to solve problems around him.

LinkedIn

Related Article - Python Palindrome

  • Reverse Integer in Python