Palindrome string is a string that reads same from both directions – forward and backward. For example, the string, ‘ROTOR‘, is a palindrome because it reads same from both forward and backward directions. Whereas ‘MOTOR’ is not a palindrome because it does not read same from both directions.
Check Palindrome by Reversing the String
For a palindrome string, the original string and its reversed one will be the same.
str = input("Enter a string: ")
if (str == str[::-1]):
print("\"%s\" is a palindrome." % str)
else:
print("\"%s\" is not a palindrome." % str)
The above program first reversed the input string by the ‘str[::-1]‘ statement. Then it compares the reversed string with the original one. If they are equal then the input string is a palindrome one, otherwise, not. Here is the output of this program.
$ python3 test.py
Enter a string: step on no pets
"step on no pets" is a palindrome.
$ python3 test.py
Enter a string: step on no pet
"step on no pet" is not a palindrome.
By Comparing the Characters
For a palindrome string, the first character will be the same as the last one, second character with the second last one and so on. If any comparison fails, then the string is not a palindrome. This logic is implemented in the code snippet below.
def is_palidrome(str):
length = len(str)
for i in range(0, int(length/2)):
if (str[i] != str[length -i -1]):
return False
return True
str = input("Enter a string: ")
if (is_palidrome(str) == True):
print("\"%s\" is a palindrome." % str)
else:
print("\"%s\" is not a palindrome." % str)