Python Determine if a string is a palindrome

Document 对象参考手册Python3 Examples

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))

Code explanation:

  1. s.lower().replace(" ", ""): First, convert the string to lowercase and remove all spaces to ensure case and spaces are ignored during comparison.
  2. s[::-1]: This is a slicing operation in Python, used to reverse the string.
  3. return s == s[::-1]: Compare the original string with the reversed string; if they are the same, returnTrue, otherwise returnFalse。

Output result:

Example

True

Document 对象参考手册Python3 Examples

Other extensions