Improved Palindrome Checker with Python

Oliver Lövström
Internet of Technology
3 min readJan 29, 2024

In our last article, we challenged ourselves to improve the is_palindrome function of ignoring spaces, punctuation, and case sensitivity. Here’s the solution.

Photo by Jessicah Hast on Unsplash

If you missed the original implementation, you can find it here:

Solution

The improved is_palindrome function now takes an additional parameter, advanced, which, when set to True, will preprocess the phrase by removing non-alphanumeric characters and converting it to lowercase. This makes our function more versatile and robust. Here's the updated function:

def is_palindrome(phrase: str, advanced: bool) -> bool:
"""Check if phrase is a palindrome.

:param phrase: The phrase to check if it is a palindrome.
:param advanced: If `True`,
remove non-alphanumeric characters and convert to lowercase.
:return: `True` if the phrase is a palindrome.
"""
if advanced:
# Remove non-alphanumeric characters and convert to lowercase.
phrase = ''.join(char.lower() for char in phrase if char.isalnum())
return phrase == phrase[::-1]

Full Code

We’ve also updated the main script to include the advanced boolean parameter, giving users the option to enable it through a command-line flag. Below is the full code with these improvements:

"""Palindrome checker."""
import argparse


def is_palindrome(phrase: str, advanced: bool) -> bool:
"""Check if phrase is a palindrome.

:param phrase: The phrase to check if it is a palindrome.
:param advanced: If `True`,
remove non-alphanumeric characters and convert to lowercase.
:return: `True` if the phrase is a palindrome.
"""
if advanced:
# Remove non-alphanumeric characters and convert to lowercase.
phrase = ''.join(char.lower() for char in phrase if char.isalnum())
return phrase == phrase[::-1]


def main(phrase: str, advanced: bool) -> None:
"""Palindrome checker main function.

:param phrase: The phrase to check if it is a palindrome.
:param advanced: If `True`,
remove non-alphanumeric characters and convert to lowercase.
"""
if is_palindrome(phrase, advanced):
print(f"The phrase {phrase} is a palindrome.")
else:
print(f"The phrase {phrase} is NOT a palindrome.")


if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Palidrome checker.")

PHRASE_HELP = "The phrase to check if it is a palindrome"
parser.add_argument("phrase", type=str, help=PHRASE_HELP)

ADVANCED_HELP = "Enable advanced checking (ignores spaces, punctuation, and case)"
parser.add_argument("-a", "--advanced", action='store_true', help=ADVANCED_HELP)


args = parser.parse_args()
main(args.phrase, args.advanced)

Testing the Enhanced Checker

Now that our palindrome checker has been enhanced let’s test it with the phrases we mentioned in the previous article. Try running the script with both regular and advanced options to see how it performs:

$ python easy/palindrome_checker.py "No lemon, no melon"
The phrase No lemon, no melon is NOT a palindrome.

$ python easy/palindrome_checker.py "No lemon, no melon" -a
The phrase No lemon, no melon is a palindrome.

Final Words

Congratulations! You’ve successfully upgraded the palindrome checker to handle more complex cases. Remember, you can find all the code from the Python Projects series on GitHub.

Further Reading

If you want to learn more about programming and, specifically, Python and Java, see the following course:

Note: If you use my links to order, I’ll get a small kickback. So, if you’re inclined to order anything, feel free to click above.

--

--