Python strings and palindrome checks
Normalize text before comparing characters.
Python
def is_palindrome(text):
cleaned = text.lower().replace(" ", "")
return cleaned == cleaned[::-1]
print(is_palindrome("Never odd or even"))
print(is_palindrome("Python"))
assert is_palindrome("") is TrueOutput
True False
Explanation
Strings are immutable sequences. A slice creates a new string; [::-1] reverses its order.
This simple palindrome rule ignores case and literal spaces. It does not remove punctuation or normalize Unicode combining characters. Defining the rule first prevents surprising results.
Explore the dry run
Guided walkthroughReady
1
def is_palindrome(text):2
cleaned = text.lower().replace(" ", "")3
return cleaned == cleaned[::-1]4
5
print(is_palindrome("Never odd or even"))6
print(is_palindrome("Python"))7
assert is_palindrome("") is TrueFollow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Pass the first phrase. | text = Never odd or even | — | |
| Lowercase and remove spaces. | cleaned = neveroddoreven | — | |
| The reversed cleaned string is identical. | return = True | — | |
| Print the result. | return = True | True | |
| python differs from nohtyp, so print False. | cleaned = python | True False | |
| An empty string equals its reverse under this definition. | cleaned = python | True False |
Cost and common mistakes
O(n) time and O(n) auxiliary space.
- Normalization rules depend on the problem; ignoring punctuation requires additional code.
- String slicing allocates a new string.
Try it yourself
Predict the results for 'Level' and 'hello'.
Reveal answer and reasoning
Level gives True after lowercasing; hello gives False.