Check For Palindrome In Python

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 75:-  Check For Palindrome In Python

 

A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. To check if a given string is a palindrome in Python, you can compare the original string with its reverse. If they are the same, then the string is a palindrome.

 

Here's a simple function to check for a palindrome in Python:

pythonCopy code

def is_palindrome(string):    # Remove non-alphanumeric characters and convert to lowercase    cleaned_string = ''.join(char.lower() for char in string if char.isalnum())    return cleaned_string == cleaned_string[::-1] # Example usage: text1 = "radar" text2 = "hello" print(is_palindrome(text1))  # Output: True print(is_palindrome(text2))  # Output: False

In this example, the is_palindrome() function takes a string as input and removes all non-alphanumeric characters (such as spaces, punctuation, etc.) using a list comprehension and the isalnum() method. It then converts the cleaned string to lowercase.

Finally, it compares the cleaned string with its reverse (cleaned_string[::-1]) using the == operator. If the original string and its reverse are the same, the function returns True, indicating that the string is a palindrome; otherwise, it returns False.

Keep in mind that this implementation is case-insensitive and ignores spaces and punctuation. If you want a case-sensitive palindrome check or need to handle specific characters differently, you can modify the function accordingly.

8. String

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?