Python .replace()错误

时间:2012-07-27 23:55:28

标签: python

在Python中,我打开一个文本文件并逐行读取,并在评估之前删除()行。 当我评估该行时,我有一个if语句来检查该行是否是“随机”,然后将一个随机数放入一个名为genRandom的变量中。我的代码中有另一行看起来像这样:

thisLine.replace("genRANDOM",genRandom) #Replace genRANDOM with the random number

在每一行上,它似乎都可以正常工作。在输入文本文件中,我有一行如下所示:

-genRANDOM

每当我的脚本评估该行时,我都会收到此错误:

Traceback (most recent call last):
  File "D:\Mass Storage\pythonscripts\TurnByTurn\execute.py", line 37, in <module>
    thisLine.replace("genRANDOM",genRandom) #Replace genRANDOM with the random number
TypeError: expected a character buffer object

我该如何解决这个问题?提前谢谢!

1 个答案:

答案 0 :(得分:2)

您告诉thisLine.replace将数字"genRANDOM"替换为genRandom。这不起作用,因为它“需要一个字符缓冲区对象”(例如字符串),而不是数字。

请尝试str(genRandom),将其变为字符串:"4"而不是4

此外,您可能希望将变量命名为其他内容; genRandom听起来像是一个为我生成随机数的函数,而不是生成的随机数。