【问题标题】:TypeError list object is not callable when trying to convert an object to a string尝试将对象转换为字符串时,TypeError 列表对象不可调用
【发布时间】:2014-07-08 16:41:28
【问题描述】:

使用 python,我导入了一个包含名称列表的 csv 文件。我想通过删除任何尾随 ;,? 字符来清理数据。我发现了 python 中的 strip 函数并决定使用它。我注意到它对文本没有任何作用。我注意到 python 不会将其视为字符串。当我运行 item is str 时,它会返回 false。当我尝试使用str(item) 时,它会说“列表”对象不可调用。

【问题讨论】:

    标签: python string csv


    【解决方案1】:

    您已将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'>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-09
      • 2015-02-25
      • 2018-05-01
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多