我制作了一个函数来检查字符串是否是回文
假设用''代替不是字母的字符串中的任何内容,但是replace()方法不起作用
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
def is_palindrome(text):
word = text.lower()
for l in word:
if l not in alphabet:
word.replace(l, '')
return word == text[::-1]
print(is_palindrome('Rise to vote, sir.'))
我希望输出为True,但实际输出为False
答案 0 :(得分:3)
重新分配。
# word.replace(l, ''): the result of the function is a string,
# so you must reassign
word = word.replace(l, '')
答案 1 :(得分:3)
为扩展HK boy的答案(并且由于我没有足够的声誉来评论),replace方法不会修改现有字符串,而是返回一个新字符串。您必须将其分配给变量(或相同的变量),才能使用带有替换字符的字符串。
word = word.replace(l, '')