Python Check Whether a String Is a Palindrome
A palindrome is a string that reads the same forwards and backwards, such as "madam" or "racecar". We can determine whether a string is a palindrome by comparing it with its reverse.
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
]
Testing
test_string
=
"A man a plan a canal Panama"
(
is_palindrome
(
test_string
)
)
Code analysis:
s.lower(): Convert all characters in the string to lowercase so that the comparison is case-insensitive.s.replace(" ", ""): Remove all spaces from the string so that strings containing spaces can be handled.s[::-1]: Reverse the string using a slice operation.s == s[::-1]: Compare the original string with the reversed string; if they are the same, returnTrue; otherwise, returnsFalse。
Output result:
True
Python3 Examples