Python program to check palindrome using one if-else : Python tutorial 22

Python Program to check if a string is palindrome or not :

What is a palindrome String ?

A String which is same in both direction i.e. if we reverse the String, it will remain same. e.g. “123454321” is a palindrome String but “12345” is not.

To check if a String is palindrome or not, first we will reverse the String and then check if it is same as the previous or not. Before that, let’s take a look into the slicing operation in python :

Python Slicing operation :

Using python slicing, we can extract one part of a String , lets take a look into the following example :

str = "12345"

print str[1:3:1]

print str[2:0:-1]

print str[::1]

print str[::-1]
It will print the following output :

23
32
12345
54321
str[1:3:1] means it will take the string from character position 1 to 2. “1” means it will read from left to right. Similarly “-1 “ means it will read from right to left. str[2:0:-1] will read from character position “2” to “1” in reverse direction.

If first and second parameter is not mentioned, it will take the full string . Now, to check for palindrome, we will reverse the String and check if it is same as the original or not.

str1 = "123454321"
 
if str1 == str1[::-1] :
     print "Palindrome..."
else :
     print "Not palindrome..."
So, using only one if-else condition, we can check if a String is palindrome or not in python. 
 

One Reply to “Python program to check palindrome using one if-else : Python tutorial 22”

  1. def check_if_palindrome(some_string):
    return True if (some_string == some_string[]::-1]) else False

Leave a Reply