A string is palindrome if we read it from end to the beginning and it is the same as begin to end. The logic to detect wheter a word is palindrome or not in programming is very simple, you need to basically revert the string and compare it with the original one. If the strings are equal (the filtered and the reversed filtered string) then the string is palindrome, pretty easy right? In this article, we'll show you how to follow the mentioned logic with a Python function easily.
Using an unintuitive syntax
The logic with the not so easy to read syntax is reversing the string with the [::-1]
slicing syntax and comparing it with the original string:
myString = "eye"
# Prints in this case "Is Palindrome"
if str(myString) == str(myString)[::-1]:
print "Is Palindrome"
else:
print "Is not Palindrome"
The str()
method of Python forces the variable type to a string, so the given parameter will be a string that you can compare with another one and to reverse using the [::-1]
syntax, which is the same as:
myString = str("eye")
# Prints in this case "Is Palindrome"
if myString == myString[::-1]:
print "Is Palindrome"
else:
print "Is not Palindrome"
Alternatively, you can create a method with the same logic:
def isPalindrome(myString):
return myString == myString[::-1]
Using an easier to read syntax
If you don't like the previous syntax, you can follow the same logic with the reversed method of Python:
myString = str("eye")
# Prints in this case "Is Palindrome"
if myString == ''.join(reversed(myString)):
print "Is Palindrome"
else:
print "Is not Palindrome"
Happy coding !