pysnippets.strings.is_palindrome
Check if a string is a palindrome
is_palindrome(text: str) -> bool
Check whether text reads the same reversed, ignoring case, spaces and punctuation.
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] 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")FalseEdit 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).
python 3.14 · in your browser
Loading Python 3.14 in your browser (≈7 MB, cached after the first time)…
Tab inserts four spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the examples.
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
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from 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.