You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

循环中出现TypeError: 'str' object is not callable错误的求助

问题分析与解决

错误原因

你遇到的 TypeError: 'str' object is not callable,根源是变量名与Python内置函数重名:
在循环内部你定义了 str="",这行代码把Python内置的 str() 类型转换函数覆盖成了空字符串变量。第一次循环执行时,str() 函数还没被覆盖,所以能正常运行;但从第二次循环开始,str 已经变成字符串对象,再调用 str(i) 就相当于尝试调用一个字符串,自然触发报错。

修复步骤

  1. 修改冲突变量名
    把代码中的 str="" 改成其他不与内置函数重名的变量名,比如 my_str="":
# 原代码
str=""
# 修改后
my_str=""
  1. 优化函数定义位置
    不要在 for col in df.columns 循环内部定义 remove 函数,每次循环重复定义函数属于冗余操作,把它移到循环外部:
# -*- coding: utf-8 -*-
def remove(x, replacer):
    global count
    count2=0
    for i in x:
        if f"'{i}'" == ascii(i):
            pass
        else:
            count=count+1
            print("flag hit")
            TestText2 = x.encode('utf8')
            print(TestText2,"\n")
            x=x.replace(i,replacer)
            
    return x

mi=[]
ni=[] 
for col in df.columns:
    zxt=df[col].tolist()
    for i in zxt:
        mi.append("") if(pd.isnull(i)) else mi.append(str(i))
    row3=""
    row2=""
    count=0
    my_str=""
    print("For Column",col)
    for row in mi:
        # 接收函数返回的修改后的值
        row = remove(row,'')
        ni.append(row)
    print("characters out of order for",count,"times")
    mi.clear()
  1. 修复值传递问题
    原代码中调用 remove(row,'') 后直接 ni.append(row),但字符串是不可变类型,函数内部的修改不会影响原变量,必须把函数返回的新值赋值给 row 后再添加到 ni 中。

内容的提问来源于stack exchange,提问作者KIdutta97

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 14:36:34