Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Check Whether a String Is a Palindrome

Python Check Whether a String Is a Palindrome

Document Object Reference Manual Python3 Examples

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"

print

(

is_palindrome

(

test_string

)

)

Code analysis:

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

Output result:

Example

True

Document Object Reference Manual Python3 Examples