fluttersmith/py-snippetsGitHub ↗

Check if a string is a palindrome

Check whether text reads the same reversed, ignoring case, spaces and punctuation.

Strings#text#validationO(n) time✓ 3 examples pass on 3.11–3.14

A man, a plan, a canal: Panama! is a palindrome once you ignore everything but the letters.

is_palindrome.py✓ ruff · mypy --strict
def is_palindrome(text: str) -> bool:
    """Return ``True`` if ``text`` is the same reversed, ignoring case and punctuation."""
    chars = [c for c in text.casefold() if c.isalnum()]
    return chars == chars[::-1]
  1. [::-1] is a reversed copy
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> is_palindrome("taco cat")Truepassed on Python 3.11 to 3.14: >>> is_palindrome("A man, a plan, a canal: Panama!")Truepassed on Python 3.11 to 3.14: >>> is_palindrome("python")False
Edit the function or the examples and run the doctests here, on Python 3.14. Python loads only when you click (about 7 MB, cached after the first time).

How it works

  • Keep only letters and digits, casefolded.
  • [::-1] makes a reversed copy, and == compares the two.

Complexity: O(n) time, O(n) space

Importfrom pysnippets.strings.is_palindrome import is_palindromeNo dependencies: copy is_palindrome.py into your project, or clone the repo.

Adapted from palindrome in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Renamed to is_palindrome; no regex; typed. Suggest an edit.