loading...

Check a String is Palindrome in Python

serhatteker profile image Serhat Teker Originally published at tech.serhatteker.com on ・1 min read

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:

#!/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!

Posted on by:

serhatteker profile

Serhat Teker

@serhatteker

Uomo Universale | Software Engineer | Entrepreneur | builds systems | py:js:go |

Discussion

markdown guide