Python · Course navigation

Python strings and palindrome checks

Normalize text before comparing characters.

On this page
Before you start

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

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 True
Output
True
False

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1def is_palindrome(text):
2 cleaned = text.lower().replace(" ", "")
3 return cleaned == cleaned[::-1]
4
5print(is_palindrome("Never odd or even"))
6print(is_palindrome("Python"))
7assert is_palindrome("") is True

Follow 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.

Further reading