Python 中的回文检测

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

回文是一个单词、短语、数字或其他字符序列,从前往后读和从后往前读都一样。例如,“racecar”是一个回文,因为当你颠倒这个单词时,它仍然拼写为“racecar”。在这个挑战中,你将编写一个函数来检查给定的字符串是否为回文。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python/BasicConceptsGroup -.-> python/booleans("Booleans") python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/ModulesandPackagesGroup -.-> python/using_packages("Using Packages") python/ModulesandPackagesGroup -.-> python/standard_libraries("Common Standard Libraries") subgraph Lab Skills python/booleans -.-> lab-13704{{"Python 中的回文检测"}} python/comments -.-> lab-13704{{"Python 中的回文检测"}} python/lists -.-> lab-13704{{"Python 中的回文检测"}} python/tuples -.-> lab-13704{{"Python 中的回文检测"}} python/function_definition -.-> lab-13704{{"Python 中的回文检测"}} python/importing_modules -.-> lab-13704{{"Python 中的回文检测"}} python/using_packages -.-> lab-13704{{"Python 中的回文检测"}} python/standard_libraries -.-> lab-13704{{"Python 中的回文检测"}} end

回文

编写一个函数 palindrome(s),它接受一个字符串 s 作为唯一参数,如果 s 是回文则返回 True,否则返回 False。在检查回文时,你的函数应忽略大小写和非字母数字字符。

要解决这个问题,你可以按照以下步骤进行:

  1. 使用 str.lower() 将字符串转换为小写。
  2. 使用 re.sub() 从字符串中删除所有非字母数字字符。
  3. 使用切片表示法将结果字符串与其反转后的字符串进行比较。
from re import sub

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

总结

在这个挑战中,你学习了如何检查一个给定的字符串是否为回文。你使用了 str.lower()re.sub() 将字符串转换为小写并移除非字母数字字符,然后使用切片表示法将结果字符串与其反转后的字符串进行比较。