No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Python Palindrome Checker

by Khaleel O.
January 11, 2022
in Python
Reading Time: 3 mins read
A A
Python Palindrome Checker
Python Palindrome Checker

Hi! Let’s code a Python Palindrome Checker. We will be using Python 3.8.10. Let’s go! ✨🔥⚡

A palindrome is a word or sentence that reads the same backward and forward. We can accomplish this solution in one line:

palindrome = lambda s: \
    ''.join(e for e in s.lower() if e.isalnum()) == \
    ''.join(e for e in s[::-1].lower() if e.isalnum()) 

print(palindrome("level"))
print(palindrome("eyes"))
print(palindrome("ev3"))
print(palindrome("nurses run"))
print(palindrome("A man, a plan, a canal, Panama!"))
print(palindrome("Sator Arepo Tenet Opera Rotas"))
print(palindrome("72911927"))
print(palindrome("Z"))

#output
#True
#False
#False
#True
#True
#True
#True
#True

Let’s explain what is happening here:

  1. Recall that a lambda function in Python is an inline function with one expression. In this case we are simply comparing the original string s with its reverse s[::-1]. That is the basic comparison that this lambda function is performing. But it is doing a few more things that will help our code handle different types of input:
    • The list comprehension ”.join(e for e in s.lower() if e.isalnum()) has the effect of stripping punctuation and whitespace and converting the text to lowercase before returning the same string s in the normal direction.
    • The list comprehension ”.join(e for e in s[::-1].lower() if e.isalnum()) is doing the same but on the reverse of the original string before returning the reverse of the initial string s stripped of punctuation, whitespace and in lowercase.
    • We do this checking so that our code can be more versatile in handling different types of input
  2. The lambda function palindrome will accept one parameter s and return True if the s and its reverse match (palindrome) or False if they don’t (not a palindrome).
  3. We provide 7 test cases with the possible ways the input can be presented to the script. We are able to detect palindromes even if punctuations, whitespaces, whole sentences, letters or numbers are in the initial string. Great isn’t it?

When the code executes we will get a list of True or False values, depending on if the word, number or sentence supplied to the lambda function palindrome is, in fact, a palindrome or not.

We can do a bit more to make this program better too! We can introduce a loop that takes a string from the user and checks to see if it is a palindrome:

def main():
    s = str(input('Enter a String: '))
    palindrome = lambda s: \
        ''.join(e for e in s.lower() if e.isalnum()) == \
        ''.join(e for e in s[::-1].lower() if e.isalnum()) 

    if palindrome(s):
        print(f"{s} IS A PALINDROME!")
    else:
        print(f"{s} IS NOT A PALINDROME!")


if __name__=='__main__':
    c =""
    while c != 'quit':
        main()
        c=str(input('Exit? (y or n): '))
        if c=='y' or c=='ye' or c=='yes':
            c='quit'
        elif c== 'n' or c=='no':
            pass

See what we did? We introduced a loop which allows us to test any amount of cases before the program exits. Awesome!

We hope that helped. Check out our List Comprehension Tutorial HERE. Thanks for reading! 👌👌👌

Tags: palindrome
Previous Post

Insertion Sort Python Explained

Next Post

Levenshtein Distance in Python

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy