Check a String is Palindrome in Python
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:''.join(list(reversed(string)))
.- With
==
we compare the equality, then returningTrue
orFalse
.
Yes it is so simple and elegant in python.
Type Check
Actually for a better program before that method we should check that the given
value is string
type or not:
def is_string(string):
if not isinstance(string, str):
raise TypeError("Input must be a string.")
Manual Testing
If we want to see all of them in action together:
|
|
if you run this code you will see:
user@host $ ./check_palindrome.py
True
Info
We should write tests and not use print as debugging, but this is a short showcase.
All done!
Subscribe
Read Related