我们可以使用正则表达式来检测字符串是否为回文。
首先,我们可以使用正则表达式 [^A-Za-z0-9]
来匹配所有的非字母数字字符。然后,我们可以使用 re.sub
函数来将这些字符替换为空字符串,从而得到只包含字母数字的字符串。
最后,我们可以将得到的字符串反转,然后将反转后的字符串与原字符串进行比较。如果相同,则该字符串为回文,否则不是。
代码示例如下:
import re
def is_palindrome(s):
s = s.lower()
s = re.sub(r'[^A-Za-z0-9]', '', s)
return s == s[::-1]
print(is_palindrome("A man, a plan, a canal: Panama"))
print(is_palindrome("race a car"))
输出结果为:
True
False