如何检查一个字符串是否是回文串

3

以下是我的代码。我是一名经验不足的程序员,我认为问题出在.join(reversed())这一部分。但是,我想不出具体原因。我需要别人再次检查一下,可能是我漏掉了什么。

def is_palindrome(alist):
    truth = []
    for i in alist:
        i.lower()
        i.replace(" ","")
        x = "".join(reversed(i))
        if i == x:
            truth.append(True)
        else:
            truth.append(False)
    return truth
test_list = ['Stats', 'A nut for a jar of Tuna', 'I eat apples']
print(is_palindrome(test_list))
print(test_list)

给出的结果是:
[False, False, False]

它应该是:

[True,True,False]

有没有人知道我哪里出错了?


你的问题标题有些晦涩。类似“如何检查一个字符串是否为回文”这样更加直接明了。 - benbotto
之前的标题是“我在使用reversed()时出了什么问题” - Qwerty
2个回答

6

.lower().replace(...) 都不是原地修改(in place)的操作。

def is_palindrome(alist):
    truth = []
    for i in alist:
        i=i.lower()
        i=i.replace(" ","")
        x = "".join(reversed(i))
        truth.append(i == x)
    return truth
test_list = ['Stats', 'A nut for a jar of Tuna', 'I eat apples']
print(is_palindrome(test_list))
print(test_list)

2
truth.append(i == x) - Chris_Rands

4
lower()replace()函数不是原地修改的。
必须将它们的返回值赋给i
i=i.lower()
i=i.replace(" ","")

输出:

[True, True, False]                                
['Stats', 'A nut for a jar of Tuna', 'I eat apples']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接