无法弄清楚如何在回文检查器中实现元组

Can't figure out how to implement a tuple in a palindrome checker

所以我正在从一本书中学习 python,我在 input/output 部分,其中提供了一个检查回文的代码示例,但它仅适用于一个字。之后它询问我是否可以通过让一个元组包含禁用字符来改进代码,以便它可以检查是否像“先生,起来投票”这样的句子。是回文。我已经用了好几次了,我只是想不通应该如何实施它。

示例代码:

def reverse(text):
    return text[::-1]

def is_palindrome(text):
    return text == reverse(text)

something = input("Enter text: ")
if is_palindrome(something):
    print("Yes, it is a palindrome")

else:
    print("No, it is not palindrome")

我尝试过的事情:

def reverse(text):
    return text[::-1]

def sanitize(text):
    text = text.lower
    forbidden = (" ", ".", ",", "!", "?")
    if forbidden in text:
        text.replace(forbidden, "")
    return text

something = input("Enter text: ")

def is_palindrome(text):
    text = sanitize(text)
    return text == reverse(text)

if is_palindrome(something):
    print("Yes, it is a palindrome")

else:
    print("No, it is not palindrome")

当然这是错误的,会抛出一个错误,但我已经尝试了多次,但我就是想不通,我相信答案很简单,但我找不到

像这样实现 sanitize 可能更有效(不使用额外的模块):

def sanitize(text):
  forbidden = (" ", ".", ",", "!", "?")
  tl = []
  for c in text:
    if not c in forbidden:
      tl.append(c)
  return ''.join(tl)

当然,forbidden变量可以是列表、元组或集合。

使用列表理解更简洁,但性能上的任何差异(无论哪种方式)都可能是微不足道的。

def sanitize(text):
  return ''.join([c for c in text if c not in (" ", ".", ",", "!", "?")])

我发现您的代码存在一些问题。

text.lower 应该改为text.lower()。您应该使用 for 循环遍历 forbidden 。并且 text 应该更新为 text.replace(c, “”) 并且 c forbidden 中的每个值。这应该是代码

def reverse(text):
    return text[::-1]

def sanitize(text):
    text = text.lower()
    forbidden = (" ", ".", ",", "!", "?")
    for c in forbidden:
        text = text.replace(c, "")
    return text

something = raw_input("Enter text: ")

def is_palindrome(text):
    text = sanitize(text)
    return text == reverse(text)

if is_palindrome(something):
    print("Yes, it is a palindrome")

else:
    print("No, it is not palindrome")