Python strings and palindrome checks
Normalize text before comparing characters.
On this page
Functions and slicing.
- Normalize text before comparing characters.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
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 TrueTrue False
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
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 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 |
Behind the scenes
How Python processes this code
Python runs this source through its interpreter. It creates objects for values and resolves names as each statement runs.
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.