TypeError: 列表对象不可调用,转换对象为字符串时出现错误

1 投票
1 回答
2271 浏览
提问于 2025-04-18 12:31

我在用Python的时候,导入了一个包含名字的csv文件。我想把数据整理一下,去掉名字后面多余的;,?这些字符。我了解到Python有一个叫做strip的函数,可以用来处理这个问题。可是我发现这个函数对我的文本没有任何作用。我注意到Python并没有把它当作字符串来处理。当我运行item is str时,它返回的是false。然后我尝试用str(item),结果却提示'list'对象不可调用。

1 个回答

6

你把 str 这个名字重新用在了一个列表对象上。这样做不好,因为你覆盖了内置的类型:

>>> str(42)
'42'
>>> str = ['foo', 'bar']
>>> str(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable

要检查一个对象的类型,正确的方法是使用 isinstance()

isinstance(item, str)

不过在调试的时候,你也可以用 type() 来查看对象的类型,或者用 repr() 来获取一个有用的 Python 字面量表示(如果有的话,没的话会给出适合调试的表示):

>>> str = ['foo', 'bar']
>>> type(str)
<type 'list'>
>>> print repr(str)
['foo', 'bar']
>>> del str
>>> type(str)
<type 'type'>
>>> print repr(str)
<type 'str'>

撰写回答