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 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.")

Manual Testing

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/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()

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!