Python常见错误—“TypeError: ‘str‘ object is not callable“

报错示例:

students=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
str=[1,2,3,4,5,6]


print("\n列表转元组:\n",tuple(students))
print("\n列表转字符串:\n",str(students))

运行上面代码,会出现下面报错提示:

 原因分析:

1、str(value) 是一个内建的系统函数,用于将一个数值型转换为字符串。

2、用户仍然可以使用str进行变量定义,如str="hello"

3、在定义了str变量后,由于名称相同,所以系统内建的str(value)函数会被解释成用户自定义的变量str,从而导致报错:“TypeError: 'str' object is not callable“

解决方案:

1、删除str变量,del str,设置其他变量名(提示:定义的变量名,最好不要与 Python 的底层函数重名。)

del str
students=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
list_str=[1,2,3,4,5,6]

print("\n列表转元组:\n",tuple(students))
print("\n列表转字符串:\n",str(students))

运行上面代码,结果:

2、重启交互环境,设置其他变量名。

猜你喜欢

转载自blog.csdn.net/sodaloveer/article/details/129586726