Write a Python script to check if a given string is a palindrome (a word or phrase that reads the same forwards and backwards)?
Here is an example of a Python script that checks if a given string is a palindrome:
def is_palindrome(word): # Reverse the word word_reverse = word[::-1] # Check if the word is equal to its reverse if word == word_reverse: return True else: return False # Test the function word = "madam" if is_palindrome(word): print(word + " is a palindrome.") else: print(word + " is not a palindrome.")
The method is palindrome in this script takes a string as an argument, reverses it using slicing, compares it to the original text, returns True if they match, otherwise returns False. Additionally, you can reverse the string using the built-in function reversed() and rejoin the reversed string to the original string using join().
def is_palindrome(word): # Reverse the word word_reverse = ''.join(reversed(word)) # Check if the word is equal to its reverse if word == word_reverse: return True else: return False # Test the function word = "madam" if is_palindrome(word): print(word + " is a palindrome.") else: print(word + " is not a palindrome.")
You can also skip over the punctuation and spaces while looking for palindromes. The isalnum() and join() functions in Python can be used to determine whether the characters are alphanumeric and to join those that are.
def is_palindrome(word): # Remove spaces and punctuations and join the alphanumeric characters word = ''.join([c.lower() for c in word if c.isalnum()]) # Reverse the word word_reverse = word[::-1] # Check if the word is equal to its reverse if word == word_reverse: return True else: return False # Test the function word = "A man, a plan, a canal: Panama" if is_palindrome(word): print(word + " is a palindrome.") else: print(word + " is not a palindrome.")
Post a Comment