Home
Map
Palindrome MethodCheck words and sentences to see if they are palindromes. Use a while true loop and handle spaces and punctuation.
Python
This page was last reviewed on Sep 15, 2022.
Palindrome. A palindrome reads the same forwards and backwards. Some common words, like "level" are palindromes. But some entire sentences are also palindromes.
Method info. We can check palindromes in Python with a simple method. We can loop over a string, checking its ends, and moving inward, on each iteration.
Example. To check for a palindrome, we use a loop to consider the start and end characters of a string together. We move inwards until we are at the center.
And If both halves of the string have equal characters, we have a palindrome.
Detail In this list, I specify an assortment of known palindromes (like "civic"). Punctuation and whitespace is included.
Detail With this method, we create a dictionary to replace all punctuation with spaces. It also lowercases letters.
Dictionary
Detail This method applies the dictionary created by maketrans to remove unwanted characters. Replace then eliminates spaces.
String translate
Info We pass the reduced strings (which have no punctuation, capital letters or whitespace) to the is_palindrome method.
def
def is_palindrome(value): min = 0 max = len(value) - 1 # Scan string for letter equality at each end. # ... Move indexes closer to the center after each check. while True: # Return true if all characters were checked. if min > max: return True; a = value[min] b = value[max] # Return false is characters are not equal. if a != b: return False; # Move inwards. min += 1 max -= 1 lines = ["civic", "A man, a plan, a canal: Panama.", "A Toyota. Race fast, safe car. A Toyota.", "Cigar? Toss it in a can. It is so tragic.", "Dammit, I'm mad!", "Delia saw I was ailed.", "Desserts, I stressed!", "Draw, O coward!", "Lepers repel.", "Live not on evil.", "Lonely Tylenol.", "Murder for a jar of red rum.", "Never odd or even.", "No lemon, no melon.", "Senile felines.", "So many dynamos!", "Step on no pets.", "Was it a car or a cat I saw?", "Dot Net Perls is not a palindrome.", "Why are you reading this?", "This article is not useful."] # Use to translate punctuation to spaces. # ... Changes uppercase to lowercase. dict = str.maketrans(",:.'!?ABCDEFGHIJKLMNOPQRSTUVWXYZ", " abcdefghijklmnopqrstuvwxyz") for line in lines: # Change all punctuation to spaces. reduced = line.translate(dict) # Remove all spaces. reduced = reduced.replace(" ", "") # See if line is a palindrome. if is_palindrome(reduced): print("Palindrome: ", line) else: print("Not palindrome:", line)
Palindrome: civic Palindrome: A man, a plan, a canal: Panama. Palindrome: A Toyota. Race fast, safe car. A Toyota. Palindrome: Cigar? Toss it in a can. It is so tragic. Palindrome: Dammit, I'm mad! Palindrome: Delia saw I was ailed. Palindrome: Desserts, I stressed! Palindrome: Draw, O coward! Palindrome: Lepers repel. Palindrome: Live not on evil. Palindrome: Lonely Tylenol. Palindrome: Murder for a jar of red rum. Palindrome: Never odd or even. Palindrome: No lemon, no melon. Palindrome: Senile felines. Palindrome: So many dynamos! Palindrome: Step on no pets. Palindrome: Was it a car or a cat I saw? Not palindrome: Dot Net Perls is not a palindrome. Not palindrome: Why are you reading this? Not palindrome: This article is not useful.
A performance note. It is possible (and likely faster) to avoid preprocessing strings. We could modify is_palindrome to ignore non-letter characters.
A summary. We combined several Python methods, including maketrans, translate and the replace() method. Writing palindrome code helps us understand Python better.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 15, 2022 (image).
Home
Changes
© 2007-2024 Sam Allen.