Determining a Palindrome Using Python

Determining a Palindrome Using Python

·

2 min read

Table of contents

No heading

No headings in the article.

In this article, we will look at a python program that checks to see if a string or an integer(number) is a palindrome or not.

First let's look at what a palindrome means?

Programming.png

We will consider 2 approaches to writing this program.

APPROACH #1

Here, the program takes in an input from a user and checks if that input aligns which the conditions for it to be a palindrome or not.

# Python program that checks if a string is a palindrome 
string = input('Enter the string: ')

if string == string[::-1] :
    print('The string is a palindrome')
else:
    print('The string is not a palindrome')

APPROACH #2

This is a similar approach to the one above but involves the use of methods in python like the casefold() and reverse() method.

# Python program that checks if a string is a palindrome
string = input('Enter the string: ') # Inputs can be strings but also integers since they will be converted to and used as strings.

# The casefold() method makes the string suitable for making caseless comparisons. It returns lowercased version of the string. So all the alphabets are lowercased and thus makes it easier when reversing and comparing.
string = string.casefold()

# Reversing the string
reverse_str = reversed(string)

# Changing both strings into lists before comparing
if list(string) == list(reverse_str):
     print('The string is a palindrome')
else:
    print('The string is not a palindrome')

The python programming language is one of the most powerful languages in our modern world. To know why you should learn more in python, read this article by Python Ghana https://blog.pythonghana.org/why-you-should-learn-python