Program works, but TypeError: 'int' object is not subscriptable is received. Why?

Program works, but TypeError: 'int' object is not subscriptable is received. Why?

此程序检查字符串是否为回文,如果是,则 returns 为真。当我在 Python IDLE 中 运行 它工作正常。但是在线测试站点不接受,返回这个错误:“TypeError: 'int' object is not subscriptable

string="racecar"
def is_palindrome(string):
        if string == string[::-1]:
            return True
        else:
            return False

这是为什么?据我所知,我没有使用 int。

您显然希望您的函数只对字符串进行操作,除非您使用支持类型提示的 Python 的全新版本,否则您无法真正告诉 Python。所以直接投射到弦上。几乎任何东西都可以转换为字符串,然后无论传递什么,你的函数都会工作,或者至少抛出一个体面的错误。

def is_palindrome(string):
        string = str(string)    # add this line
        if string == string[::-1]:
            return True
        else:
            return False