如何在python中检查单词回文

  • 本文关键字:单词 回文 python python
  • 更新时间 :
  • 英文 :

def isPalindrome(word):
    n1 = word
    n2 = word[::-1]
    if n1 == n2 :
       return True
    else:
       return False

我尝试了这个,但得到类似Traceback(最近一次调用)的错误:

File "Code", line 3, in isPalindrome
TypeError: 'int' object has no attribute '__getitem__'.

这里如何处理数字?

def is_palindrome(s):
   s = str(s) 
   return s == s[::-1]

对阿南德的回答重写得稍微好一点。

注意:根据PEP 0008, python函数名应该是lowercase_separated_by_underscore,除非这破坏了本地约定。(对于那些肮脏的Java程序员https://www.python.org/dev/peps/pep-0008/#function-names)

在使用单词之前使用str()将单词转换为字符串。例子——

def isPalindrome(word):
    n1 = str(word)
    n2 = str(word)[::-1]
    if n1 == n2 :
       return True
    else:
       return False

如果word是整型,它将被转换为字符串。否则,如果它已经是字符串,它仍然是字符串。

可以扩展到测试一个句子:

import re
def is_palindrome(sentence):
    sentence = re.sub(r'[^a-zA-Z0-9]','',str(sentence)).lower()
    return sentence == sentence[::-1]

最新更新