DEV Community

Serhat Teker
Serhat Teker

Posted on • Originally published at tech.serhatteker.com on

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]
Enter fullscreen mode Exit fullscreen mode
  • [::-1] slice reverses the string. It is equal to: ''.join(list(reversed(string))).
  • With == we compare the equality, then returning True or False.

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.")
Enter fullscreen mode Exit fullscreen mode

Manual Testing

If we want to see all of them in action together:

#!/usr/bin/env python3
# check_palindrome.py


def is_string(string):
    if not isinstance(string, str):
        raise TypeError("Input must be a string.")


def is_palindrome(string):
    return string == string[::-1]


def main():
    string = "tenet"
    is_string(string)

    print(is_palindrome(string))
    return is_palindrome(string)


if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

if you run this code you will see:

user@host $ ./check_palindrome.py
True
Enter fullscreen mode Exit fullscreen mode

INFO:
We should write tests and not use print as debugging, but this is a short showcase.

All done!

Top comments (0)