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

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