If you have any query feel free to chat us!
Happy Coding! Happy Learning!
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.
Comments: 0