11. Palindrome check
A palindrome reads the same forwards and backwards, like level or noon. A phrase can be one too: keep only its
letters and digits, put the letters in lower case, and see whether the result reads the same both ways.
"A man, a plan, a canal: Panama" becomes "amanaplanacanalpanama", which does.
Write a function is_palindrome(text) that takes a string text and returns True if it is a palindrome in this
sense, or False if it isn't:
- Only letters and digits count. Spaces, punctuation and symbols such as
_are left out. - Ignore case:
Randrcount as the same letter. - Digits count just like letters:
"0P"becomes"0p", which isn't a palindrome. - If nothing is left (an empty string, or only spaces and punctuation), the answer is
True: an empty string reads the same both ways.
Example 1
text = "A man, a plan, a canal: Panama"TrueExample 2
text = "race a car"FalseExample 3
text = "0P"FalseConstraints
texthas 0 to 200 characters.- They are English letters, digits, spaces and punctuation.
Submit also runs 12 more tests you can't see.
Practises Strings (lesson 4).
- Build a cleaned copy first: loop over
textand keep each characterchfor whichch.isalnum()isTrue(a letter or a digit), addingch.lower(). cleaned[::-1]is the cleaned string reversed: a slice with a step of -1. Returncleaned == cleaned[::-1], which is alreadyTrueorFalse.- Use
isalnum(), notisalpha(): digits count, so"0P"givesFalse. When nothing is kept,""equals its reverse and the answer isTruewith no special case.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def is_palindrome(text):
"""Check whether text reads the same both ways.
text: str, letters, digits, spaces and punctuation;
may be empty
Returns: bool, True if its letters and digits read the
same both ways, ignoring case, else False
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.