OSCC · 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

Recommended snippets

  • String to words

    Python, String

    Converts a given string into a list of words.

  • String is anagram

    Python, String

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

  • Pad number

    Python, String

    Pads a given number to the specified length.