Python String Practice: Check for Palindromes

A palindrome reads the same forwards and backwards. Checking one is a compact way to practise string methods and slicing. This exercise compares each word with its reversed copy and ignores letter case.

Before you start: Strings, for loops and comparison with ==.

Your task

For each word, print True if it reads the same backwards when you ignore upper and lower case, and False otherwise.

Starter code

words = ["level", "python", "Radar"]

# Print True or False for each word.

Expected result

True
False
True
Open this exercise

Loads the starter in the workspace. Save or export existing work first. Return here for hints and the explanation.

Need a hint?

Convert the word to lowercase, reverse it with [::-1], then compare the two strings.

Show the complete solution and walkthrough
words = ["level", "python", "Radar"]

# Print True or False for each word.
for word in words:
    cleaned = word.lower()
    print(cleaned == cleaned[::-1])
  1. Loop through words and call lower() on each. Radar becomes radar, so capital letters no longer matter.
  2. Reverse the cleaned word with cleaned[::-1]. The slice with a step of -1 returns the characters in reverse order.
  3. Print the result of cleaned == cleaned[::-1]. The output is True for level, False for python and True for Radar.

A common mistake

Comparing the original word with its reverse treats Radar and radaR as different. Using reversed() directly returns an iterator, so comparing it with a string is always False.

Try an edge case

An empty string and a single character are palindromes. Phrases with spaces or punctuation need those characters removed before comparing.

Take it one step further

Ignore spaces and punctuation so that "A man, a plan, a canal: Panama" counts as a palindrome. Hint: keep only characters where isalnum() is True.

Read the python tool guide