Categories
Python Answers

How to check for palindromes using Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *