0

我在 python 中编写了一个回文测试器,当手动输入某个包含双引号的回文时,程序会正确地将其识别为回文。但是,当我复制并粘贴同一行文本时,程序无法在将字符串与其反向字符串进行比较之前删除双括号。

这是代码:

  ### Palindrome Test ###

  import string                               # class which includes all punctuation characters 

  word = raw_input("Please enter a word or phrase:\n")

  if (len(word) <= 1):                        # if 0 or 1 character input
      print 'Sorry, ' + '"' + word + '"' + ' is too short to be a palindrome.'

  else:

      tword = word.lower()                    # make input lowercase so capital letters don't cause problems, assn to new var

      tword2 = tword.replace(' ','')          # replace spaces with empty strings to remove space asymmetry

      tword3 = list(tword2)                   # break lowercase, spaceless input into list of characters, assn to new variable

                                              # ditch punctuation in list 
      tword3 = [''.join(c for c in s if c not in string.punctuation) for s in tword3]

      fword = ''.join(tword3)                 # gives us a lowercase, spaceless, punctuationless forward string

      tword3.reverse()                        # reverse list of characters

      bword = ''.join(tword3)                 # rejoin backwards list, assn to new variable

      if bword == fword:                      # check equivalence of backwards and forwards lowercase, spaceless, punctuationless input
                                              # if equivalent, print 'yes' message with original input
          print 'YES, ' + '"' + word + '"' + ' is a palindrome.' 

      else:                                   # else, 'no' message with original input
          print 'NO, ' + '"' + word + '"' + ' is not a palindrome.' 

什么时候,例如,“甜点,姐姐?” (强调感性)。作为输入输入,它正确地返回“是”消息。当我粘贴它时,它会给出一个“不”的消息。

这是怎么回事?

编辑:我发现从本网站粘贴或 word 文档不会给我带来问题。但是,从此页面 (http://www.palindromelist.net/Desserts-sis-Sensuousness-is-stressed/) 粘贴确实会产生错误的输出。

4

1 回答 1

2

研究这个例子。您的代码工作正常,这只是清理了一下:

from string import punctuation

def is_palindrome(word):
    if len(word) <= 1:                              
        raise Exception("Sorry, '%s' is too short to be a palindrome" % word)

    lowered = ''.join(word.lower().split())
    filtered = filter(lambda x: x not in punctuation, lowered)                                  
    return filtered == filtered[::-1]
于 2013-01-18T23:43:11.787 回答