Python 字符串替换错误

ge0*_*try 6 python string replace

我有一个 python 脚本,它不断返回以下错误:

类型错误:replace() 至少需要 2 个参数(给定 1 个)

我一生都无法弄清楚是什么导致了这种情况。

这是我的代码的一部分:

inHandler = open(inFile2, 'r')
outHandler = open(outFile2, 'w')

for line in inHandler:

    str = str.replace("set([u'", "")
    str = str.replace("'", "")
    str = str.replace("u'", "")
    str = str.replace("'])", "")

outHandler.write(str)

inHandler.close()
outHandler.close()
Run Code Online (Sandbox Code Playgroud)

在双引号中看到的所有内容都需要用空替换。

所以set([u'应该看起来像

AHu*_*man 7

这是你想要做的:

for line in inHandler:
    line = line.replace("set([u'", "")
    line = line.replace("'", "")
    line = line.replace("u'", "")
    line = line.replace("'])", "")

outHandler.write(line)
Run Code Online (Sandbox Code Playgroud)

在文档中,无论在哪里说类似str.replace(old,new[,count])的东西str都是一个示例变量。事实上,str是一个内置函数,这意味着你永远不想通过将它分配给任何东西来改变它的含义。

line = line.replace("set([u'", "")
  ^This sets the string equal to the new, improved string.

line = line.replace("set([u'", "")
        ^ This is the string of what you want to change.
Run Code Online (Sandbox Code Playgroud)