Python Determine if a string is a 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 it 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().replace(" ", ""): First, convert the string to lowercase and remove all spaces to ensure case and spaces are ignored during comparison.s[::-1]: This is a slicing operation in Python, used to reverse the string.return s == s[::-1]: Compare the original string with the reversed string; if they are the same, returnTrue, otherwise returnFalse。
Output result:
Example
True
Python3 Examples