Palindrome

Python, String · Nov 2, 2020

Checks if the given string is a palindrome.

  • Use str.lower() and re.sub() to convert to lowercase and remove non-alphanumeric characters from the given string.
  • Then, compare the new string with its reverse, using slice notation.
from re import sub

def palindrome(s):
  s = sub('[\W_]', '', s.lower())
  return s == s[::-1]
palindrome('taco cat') # True

More like this

  • String to words

    Converts a given string into a list of words.

    Python, String · Nov 2, 2020

  • String is anagram

    Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).

    Python, String · Nov 2, 2020

  • How can I check if a string is empty in Python?

    Here are two quick and elegant ways to check if a string is empty in Python.

    Python, String · Aug 5, 2022