0

In Python, I open a text file and read it line-by-line, and strip() the line before evaluating it. When I evaluate the line, I have an if statement to check if the line is "random", and then puts a random number into a variable called genRandom. I have another line in my code that looks like this:

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

On every line, it seems to work ok. In the input text file, I have a line that looks like this:

-genRANDOM

Whenever my script evaluates that line, I get this error:

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

How can I fix this? Thanks in advance!

4

1 回答 1

2

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

尝试str(genRandom)将其转换为字符串:"4"而不是4.

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

于 2012-07-27T23:58:01.083 回答