30秒学会 Python 片段 · 2019年6月8日

30秒学会 Python 片段 – palindrome

Returns True if the given string is a palindrome, False otherwise.

Use s.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.

代码实现

from re import sub

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

使用样例

palindrome('taco cat') # True