Python,键入的文本和粘贴的文本会产生不同的结果。为什么?

时间:2013-01-18 22:53:10

标签: python python-2.7

我已经在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/)会产生错误的输出。

1 个答案:

答案 0 :(得分: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]