Check a String is Palindrome in Python
2 minutes read
A palindrome is any number or string which remains unaltered when reversed.
The most pythonic way to determine if a given string is a palindrome would be:
def is_palindrome(string): return string == string[::-1]
[::-1]slice reverses the string. It is equal to:
==we compare the equality, then returning
Yes it is so simple and elegant in python.
Actually for a better program before that method we should check that the given
string type or not:
def is_string(string): if not isinstance(string, str): raise TypeError("Input must be a string.")
If we want to see all of them in action together:
if you run this code you will see:
[email protected] $ ./check_palindrome.py True
We should write tests and not use print as debugging, but this is a short showcase.