A Homework Assignment

Anterra Kennedy
Atha Data Science
Published in
2 min readJul 8, 2020

April 23rd, 2020

You never really know what you know (or don’t) until you have to do it yourself. That was demonstrated yesterday when a ‘homework’ assignment was posed by the textbook I’m working through, and I got to actually problem solve and write a program myself, instead of simply learn how various features of Python work through studying example programs.

The previous example had created a program which would check whether or not a user inputted string was a palindrome. The homework assignment was then to make the program more robust and accurate, by making it ignore punctuation, spaces, and capital letters, such that “Rise to vote, sir” for example, would be recognized as the palindrome that it is. The completed assignment can be viewed here: https://github.com/anterra/learning-python/blob/master/input_and_output/io_input_homework.py

In designing how I would go about this, my first plan was to create a tuple of all the forbidden special characters, then iterate over that tuple to check if each one appeared in the input string, and if so delete it.

Then I planned to do the same with a tuple of capitalized letters, and if they appeared, replace them with lowercase versions of the same. I was trying to think of how to identify what sequence number the found capital letter held within the alphabet, so I could then replace with the same letter by calling the same position number in a lowercase alphabet tuple.

Both of these plans went through a few phases of trial and error before getting vastly simplified! First, I discovered the ‘string’ module, which includes built in ‘punctuation’ and ‘ascii_lowercase’/’ascii_uppercase’ strings. Excellent! Now I need not type out every possible punctuation mark etc.

So, I iterated over the punctuation string first and used:

text.replace(character, “”)

to delete any punctuation marks. However, when I then returned text, it was unchanged! I realized then that I must use :

text = text.replace(character, “”)

to reassign the variable as the changed version of itself, not just apply the change but not store it. I also included a separate line,

text = text.replace(“ “, “”)

to eliminate spaces, which are not included in string.punctuation.

Even further simplification came when I discovered Python’s .lower() method. No longer did I need to try to select which letter of the alphabet needed to be replaced with a lowercase version of itself, instead I could just convert the whole input string to lowercase in one simple line.

I ran the program with the example sentence, and it returned as a palindrome! It may be a very simple program, but it allowed me to get really familiar with string methods and applying a lot of the information learned so far, as well as the process of thinking through solving a problem with Python methodically and making optimization improvements, and was very satisfying!

--

--