如何在python中检查单词的回文与否

2024-04-26 11:08:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

这里怎么处理数字?你知道吗


Tags: infalsetruereturnifdef错误line
3条回答

在使用之前,使用str()将单词转换为字符串。示例-

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

如果word是int,它将被转换为string。否则,如果它已经被激活,它将保持为string。你知道吗

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

对Anands答案的非常好的重写(imho)。你知道吗

注意:根据pep0008,python函数名应该是小写的,用下划线分隔,除非这违反了本地惯例。(对于那些肮脏的Java程序员来说https://www.python.org/dev/peps/pep-0008/#function-names

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

import re

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

相关问题 更多 >