Python: Check whether a string is Palindrome or not

A palindrome is a sequence of characters which reads the same backward or forward.

For example dad, mom, kayak, a santa at nasa, anna. Not palindromes: mario, luigi, ice cream.

There is more than one way in python to check whether given string is palindrome or not. Let’s have a look.

Method 1

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

defiantly one of the shortest ways to do it.

[::-1] taking care of inverting the string and all is left is simply compare between the original to inverted string.

Method 2

Slower than the first method:

def is_palindrome():
    return my_str == ''.join(reversed(my_str))

Method 3

My least favorite but quite common (especially in other languages)

def is_palindrome():
    for i in xrange(0, len(my_str)/2):
        if my_str[i] != my_str[len(my_str)-i-1]:
            return False
    return True


Q: How can I handle case-sensitive palindrome?

A: you can use upper() when comparing the reversed and the original strings.

5 thoughts on “Python: Check whether a string is Palindrome or not

  1. Someone essentially lend a hand to make severely posts I’d state.
    That is the first time I frequented your webgsite page aand so
    far? I surprised with the rewsearch you made to create
    this particular post extraordinary. Fantastic process!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s