Lesson goal: Finding Palindromes

Previous: Comparing strings (2) | Home | Next: Palindromic squares

A "palindrome" is a word (or sentence) whose letters are the same forward as backward. Words like "kayak," "rotor," and "dad" are palindromes. There are palindromic phrases too, like "was it a car or a cat i saw." Typically, spaces and punctuation are ignored.

Let's write a program that will tell you if a word (or phrase) is a palindrome. Here's the needed logic:

  1. Read a string and convert it to lowercase for a "safe" comparison.
  2. Remove the spaces from the string
  3. Compare the original string to the reverse space-free string and see if they match.

Here are the three string functions we'll use:

Move the mouse over a dotted box for more information.

Now you try. See if you can fix the if statement to test if string b is equal to its reversed version.

Type your code here:

See your results here:

This code will not work, but here's the logic. See if you can get it working by fixing the if statement:
  1. Read a string into variable a and convert it to lowercase.
  2. Start a for-loop with the variable i from 1 to the length of a.
  3. Extract the single character at position i in string a using the string.sub function. If it's not a space (~= " ") then concatenate the character to a new string called b.
  4. At the conclusion of the for-loop, variable b contains a space-free version of the original string.
Now it's your turn. What condition would you put in the if statement to see if b is equal to its reverse? This is the "palindrome test."

Here are some test words (see Wikipedia): civic, radar, level, rotor, kayak, reviver, racecar, redder, madam, toot, boob, malayalam, pop, noon, and refer.

Here are some test phrases (Wikipedia): "Was it a rat I saw" or "Never odd or even" Dismiss.

Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.