python判断是否为回文

2100阅读 0评论2012-02-08 wenhaoz
分类:Python/Ruby

  1. # check if a phrase is a palindrome
  2. # tested with Python24 vegaseat 10sep2006

  3. def isPalindrome(phrase):
  4.     """
  5.     take a phrase and convert to all lowercase letters and
  6.     ignore punctuation marks and whitespaces,
  7.     if it matches the reverse spelling then it is a palindrome
  8.     """
  9.     phrase_letters = [c for c in phrase.lower() if c.isalpha()]
  10.     print phrase_letters # test
  11.     return (phrase_letters == phrase_letters[::-1])


  12. phrase1 = "A man, a plan, a canal, Panama!" # example with punctuation marks
  13. if isPalindrome(phrase1):
  14.     print '"%s" is a palindrome' % phrase1
  15. else:
  16.     print '"%s" is not a palindrome' % phrase1

  17. print

  18. phrase2 = "Madam in Eden I'm Adam"
  19. if isPalindrome(phrase2):
  20.     print '"%s" is a palindrome' % phrase2
  21. else:
  22.     print '"%s" is not a palindrome' % phrase2
上一篇:用python输出杨辉三角
下一篇:统计字符串中单词的个数