# Python Palindromes One-Liner

5/5 - (1 vote)
`"bob" == "bob"[::-1]`

This one-liner introduces another basic computer science term: palindromes. Similar to anagrams, palindromes are a popular coding interview question.

First things first:

## What is a Palindrome?

โA palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam or racecar or the number 10201.โ [source]

Here are a few fun examples:

• โMr Owl ate my metal wormโ
• โWas it a car or a cat I saw?โ
• โGo hang a salami, Iโm a lasagna hogโ
• โRats live on no evil starโ
• โHannahโ
• โAnnaโ
• โBobโ

Is there a short and concise one-liner solution in Python? (There is!)

But before you and I move on, I’m excited to present you my brand-new Python book Python One-Liners.

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

## Problem Formulation

The problem is the following: Given a sequence of characters (string) โ is the reverse sequence of characters the same as the original sequence (that is โ is the string a palindrome)?

• Whitespace matters, i.e., `'ann a'` is not considered a palindrome, but `'anna'` is.
• Capitalization matters, i.e., `'Anna'` is not considered a palindrome, but `'anna'` is.

## Python Palindrome Checker in One Line

```## One-Line Palindrome Checker
is_palindrome = lambda phrase: phrase == phrase[::-1]```

Listing: One-liner solution to check whether a phrase is a palindrome.

If you don’t like one-liners and lambda functions, you can also define an explicit function:

```def is_palindrome(phrase):
return phrase == phrase[::-1]```

Let’s check how this works next.

## How the Python Palindrome Checker Works

The one-liner solution does not need any external library, itโs simple and straightforward. We define a lambda function that takes a single argument `phrase` โ the string to be tested โ and returns a Boolean whether the sequence of characters remains unchanged when reversed. To reverse the string, we use slicing.

Letโs quickly recap slicing:

๐ก Slicing is a Python-specific concept for carving out a range of values from sequence types such as lists or strings. Slicing is based on the concise notation `[start:stop:step]` to carve out a sequence starting in index โ`start`โ (inclusive) and ending in index โ`end`โ (exclusive). The third parameter โ`step`โ allows you to define the step size, i.e., how many characters from the original sequence your slice will skip before taking the next character (e.g. `step=2` means that your slice will consist of only every other character). When using a negative step size, the string is traversed in reverse order.

Thus, the result of the one-liner code snippet is the following:

```## Result
print(is_palindrome("anna"))
# True

print(is_palindrome("kdljfasjf"))
# False

print(is_palindrome("rats live on no evil star"))
# True```

## Python Palindrome Checker Ignoring Whitespace and Capitalization

To check whether two strings are palindromes when ignoring capitalization and arbitrary whitespaces, first bring the string into a canonical form using `''.join(phrase.split())` and `string.lower()` to convert it to a lowercase string without whitespaces.

Then use the same expression `string == string[::-1]` to compare the string with its reverse representation using slicing with negative step size.

Here’s the code example:

```def is_palindrome(phrase):

# remove all whitespaces and lowercase string
cleaned = ''.join(phrase.split()).lower()
return cleaned == cleaned[::-1]

print(is_palindrome("Anna"))
# True

print(is_palindrome("An\n\n     n \n\ta"))
# True

```

## Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
• Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
• Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
• Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
• Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!

### 2 thoughts on “Python Palindromes One-Liner”

1. โMr Owl ate my metal wormโ
If you count blanks as chars too, the above is not a palindrome!

• Yeah, you’re right. It’s just an approximate fun palindrome… ๐
Here’s how you could fix it:

>>> s = “Mr Owl ate my metal worm”.lower().replace(” “,””)
>>> print(s == s[::-1])
True