TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to PYTHON

Python Palindrome Method: Detect Words, Sentences

Check words and sentences to see if they are palindromes. Use a while true loop and handle spaces and punctuation.
Palindrome. A palindrome reads the same forwards and backwards. Some common words, like "level" are palindromes. But some entire sentences are also palindromes. We can check these in Python with a simple method.Strings
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. If both halves of the string have equal characters, we have a palindrome.

Lines: In this list, I specify an assortment of known palindromes (like "civic"). Punctuation and whitespace is included.

Maketrans: With this method, we create a dictionary to replace all punctuation with spaces. It also lowercases letters.

Translate: This method applies the dictionary created by maketrans to remove unwanted characters. Replace then eliminates spaces.

Info: We pass the reduced strings (which have no punctuation, capital letters or whitespace) to the is_palindrome method.

Python program that checks for palindromes 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?", "The Dev Codes 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. line = line.translate(dict) # Remove all spaces. line = line.replace(" ", "") # See if line is a palindrome. if is_palindrome(line): print("Palindrome: ", line) else: print("Not palindrome:", line) Output Palindrome: civic Palindrome: amanaplanacanalpanama Palindrome: atoyotaracefastsafecaratoyota Palindrome: cigartossitinacanitissotragic Palindrome: dammitimmad Palindrome: deliasawiwasailed Palindrome: dessertsistressed Palindrome: drawocoward Palindrome: lepersrepel Palindrome: livenotonevil Palindrome: lonelytylenol Palindrome: murderforajarofredrum Palindrome: neveroddoreven Palindrome: nolemonnomelon Palindrome: senilefelines Palindrome: somanydynamos Palindrome: steponnopets Palindrome: wasitacaroracatisaw Not palindrome: dotnetCodexisnotapalindrome Not palindrome: whyareyoureadingthis Not palindrome: thisarticleisnotuseful
To detect palindromes, we scan the start and end of a string, progressing towards the center. It is possible (and possibly 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. Detecting palindromes is not that useful. But it helps us understand Python better. And that is useful.TranslateReplace
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf