Python 字符串替换错误 [英] Python String Replace Error
问题描述
我有一个 python 脚本,它不断返回以下错误:
I have a python script that keeps returning the following error:
TypeError: replace() 需要至少 2 个参数(给定 1 个)
TypeError: replace() takes at least 2 arguments (1 given)
我终其一生都无法弄清楚是什么导致了这种情况.
I cannot for the life of me figure out what is causing this.
这是我的代码的一部分:
Here is part of my code:
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()
双引号内的所有内容都需要用空替换.
Everything that is seen within double quotations needs to be replaced with nothing.
所以 set([u'
应该看起来像
So set([u'
should look like
推荐答案
这就是你想要做的:
for line in inHandler:
line = line.replace("set([u'", "")
line = line.replace("'", "")
line = line.replace("u'", "")
line = line.replace("'])", "")
outHandler.write(line)
在文档中,无论在哪里说 str.replace(old,new[,count])
之类的内容,str
都是示例变量.事实上,str
是一个内置函数,这意味着你永远不想通过将它分配给任何东西来改变它的含义.
On the documentation, wherever it says something like str.replace(old,new[,count])
the str
is an example variable. In fact, str
is an inbuilt function, meaning you never want to change what it means by assigning it to anything.
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.
这篇关于Python 字符串替换错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!