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