Python Determine if String is 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 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))

Code explanation:

  1. s.lower(): Converts all characters in the string to lowercase to ensure case-insensitive comparison.
  2. s.replace(" ", ""): Removes all spaces from the string to handle strings containing spaces.
  3. s[::-1]: Reverses the string using slicing.
  4. s == s[::-1]: Compares the original string and the reversed string; if they are the same, it returnsTrue, otherwise it returnsFalse。

Output result:

True

Document 对象参考手册Python3 Examples

Other extensions