"bob" == "bob"[::-1]
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”
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).
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
- Capitalization matters, i.e.,
'Anna'is not considered a palindrome, but
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
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.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.