Sometimes, we want to check for palindromes using Python.
In this article, we’ll look at how to check for palindromes using Python.
How to check for palindromes using Python?
To check for palindromes using Python, we can use the Python slice syntax.
For instance, we write:
def is_palindrome(n):
return str(n) == str(n)[::-1]
print(is_palindrome('abba'))
print(is_palindrome('foobar'))
to create the is_palindrome
function that takes a string n
and check if the string is the same as is and when it’s reversed.
We reversed n
with str(n)[::-1]
.
Therefore, print
should print:
True
False
respectively.
Conclusion
To check for palindromes using Python, we can use the Python slice syntax.