Write a program of palindrome in python - Program of palindrome in python language - Palindrome program - Python Programs
Palindrome Program In Python
Here's a Python program to check if a given string is a
palindrome:
Python Code:
def is_palindrome(s):
"""
Returns True if
the given string s is a palindrome, False otherwise.
"""
# Remove all
non-alphanumeric characters and convert to lowercase
s =
''.join(filter(str.isalnum, s)).lower()
# Check if the
string is equal to its reverse
return s ==
s[::-1]
Here is the Practical of the above program in Jupyter Notebook
# Example usage
print(is_palindrome("racecar")) # True
print(is_palindrome("A man, a plan, a canal,
Panama!")) # True
print(is_palindrome("hello")) # False
The is_palindrome function takes a string s as input and first removes all non-alphanumeric characters (using the filter function and the str.isalnum method) and converts the string to lowercase. Then, it checks if the resulting string is equal to its reverse (using the slicing syntax [::-1]). Finally, it returns True if the string is a palindrome, and False otherwise.
Note that this implementation considers a string with spaces and punctuation to be a palindrome if the letters are the same when reversed. If you want to consider only the letters themselves (ignoring spaces and punctuation), you can modify the function to remove those characters as well.
Comments
Post a Comment