Checking if a string is a palindrome

The reason why I like Python so much is the way I can solve some simple problems – solutions are simple and good looking. One of the examples I use to give when asked “what does it mean that code is good looking” is checking if word is a palindrome.

Here’s a brief introduction: A palindrome is a word, phrase, number, or other sequence of units that may be read the same way in either direction, with general allowances for adjustments to punctuation and word dividers. The problem is trivial, but there are multiple ways of providing the solution and only one of them is – in my oppinion – good looking.

The general idea is simple – we have to revert a string and compare it with the original one. OK, let’s do it in the most “natural” way (of course in a real life I’d use some variables, not an explicit strings):

In [1]: "abcba".reverse()
AttributeError                  Traceback (most recent call last)
/home/michal/<ipython-input-41-ddc2d097f3ec> in <module>()
----> 1 "abcba".reverse()
AttributeError: 'str' object has no attribute 'reverse'

Ouch! String does not have a reverse() method – too bad! But even if it does – in case of lists it reverses them in place, which not always is the result we want to achieve. Anyway – it’s not a good solution. How about this one:

In [2]: "abcba" == reversed("abcba")
Out[2]: False

What?! Oh, yes… A reversed() method does not create a string, but a “reversed object” instead, which can’t be compared with string.

In [3]: print reversed("abcba")
<reversed object at 0x12ba190>

The expected result can be achvieved with the following code:

In [4]: print ''.join(reversed("abcba"))

It works, but I don’t like it. Any other ideas? YES. It is called “slices”. Yes, it’s this thing with a square bracket syntax – you have to know it. But did you know that it does not only make use of two arguments (begin, end) separated with a semicolon, but it also have a third one? This syntax is called “extended slices” and works this way:

In [5]: "abcba" == "abcba"[::-1]
Out[5]: True

All you need to revert a string (or list) is a [::-1]. And it makes a shallow copy, so you don’t loose your original object. Short, simple, nice – this is why I love Python.

One thought on “Checking if a string is a palindrome

  1. Pingback: A few words about Python's extended slices |