How to check for palindrome using Python logic

A pythonic way to determine if a given value is a palindrome:

str(n) == str(n)[::-1]

Explanation:

  • We're checking if the string representation of n equals the inverted string representation of n
  • The [::-1] slice takes care of inverting the string
  • After that, we compare for equality using ==

An alternative to the rather unintuitive [::-1] syntax is this:

>>> test = "abcba"
>>> test == ''.join(reversed(test))
True

The reversed function returns a reversed sequence of the characters in test.

''.join() joins those characters together again with nothing in between.


Just for the record, and for the ones looking for a more algorithmic way to validate if a given string is palindrome, two ways to achieve the same (using while and for loops):

def is_palindrome(word):

    letters = list(word)    
    is_palindrome = True
    i = 0

    while len(letters) > 0 and is_palindrome:       
        if letters[0] != letters[(len(letters) - 1)]:
            is_palindrome = False
        else:
            letters.pop(0)
            if len(letters) > 0:
                letters.pop((len(letters) - 1))

    return is_palindrome

And....the second one:

def is_palindrome(word):

    letters = list(word)
    is_palindrome = True

    for letter in letters:
        if letter == letters[-1]:
            letters.pop(-1)
        else:
            is_palindrome = False
            break

    return is_palindrome

The awesome part of python is the things you can do with it. You don't have to use indexes for strings.

The following will work (using slices)

def palindrome(n):
    return n == n[::-1]

What it does is simply reverses n, and checks if they are equal. n[::-1] reverses n (the -1 means to decrement)

"2) My for loop (in in range (999, 100, -1), is this a bad way to do it in Python?"

Regarding the above, you want to use xrange instead of range (because range will create an actual list, while xrange is a fast generator)

My opinions on question 3

I learned C before Python, and I just read the docs, and played around with it using the console. (and by doing Project Euler problems as well :)


Below the code will print 0 if it is Palindrome else it will print -1

Optimized Code

word = "nepalapen"
is_palindrome = word.find(word[::-1])
print is_palindrome

Output: 0

word = "nepalapend"
is_palindrome = word.find(word[::-1])
print is_palindrome

Output: -1

Explaination:

when searching the string the value that is returned is the value of the location that the string starts at.

So when you do word.find(word[::-1]) it finds nepalapen at location 0 and [::-1] reverses nepalapen and it still is nepalapen at location 0 so 0 is returned.

Now when we search for nepalapend and then reverse nepalapend to dnepalapen it renders a FALSE statement nepalapend was reversed to dnepalapen causing the search to fail to find nepalapend resulting in a value of -1 which indicates string not found.


Another method print true if palindrome else print false

word = "nepalapen"
print(word[::-1]==word[::1])

output: TRUE