Python Determine if String is Palindrome
A palindrome is a string that reads the same forward and backward, such as "madam" or "racecar". We can determine whether a string is a palindrome by comparing the string with its reversed string.
Example
def is_palindrome(s):
# Convert the string to lowercase and remove spaces
s = s.lower().replace(" ", "")
# Compare the string with its reverse
return s == s[::-1]
# Test
test_string = "A man a plan a canal Panama"
print(is_palindrome(test_string))
# Convert the string to lowercase and remove spaces
s = s.lower().replace(" ", "")
# Compare the string with its reverse
return s == s[::-1]
# Test
test_string = "A man a plan a canal Panama"
print(is_palindrome(test_string))
Code explanation:
s.lower(): Converts all characters in the string to lowercase to ensure case-insensitive comparison.s.replace(" ", ""): Removes all spaces from the string to handle strings containing spaces.s[::-1]: Reverses the string using slicing.s == s[::-1]: Compares the original string and the reversed string; if they are the same, it returnsTrue, otherwise it returnsFalse。
Output result:
TrueOther extensions
Python3 Examples