Python 字符串替换错误

标签 python string replace

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

TypeError: replace() takes at least 2 arguments (1 given)

我这辈子都弄不明白是什么原因造成的。

这是我的部分代码:

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()

双引号内的所有内容都不需要替换。

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

最佳答案

这是你想要做的:

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 是一个内置函数,这意味着您永远不想通过将其分配给任何东西来改变它的含义。

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 字符串替换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26901914/

相关文章:

regex - 如何用powershell替换每行的第一部分和最后一部分

python - 将否定文本转换为python中的文本

python - 我的短递归函数执行时间太长,我该如何优化它

javascript - 检查输入字符串是否包含javascript中的数字

Java:解析字符串并将其分解为 'terms'

ruby - 为什么不匹配交替中更长的标记?

javascript - 将 Javascript Replace() 函数移植到 Objective C

python - 在 Python 中,0 ==(1 或 0)返回 False。为什么它不返回 True?

python - 定义以向量作为内键和外键的字典的字典

php - 用数组php中的空值替换空字符串