0
import random
import time
x = 1
def clear():
    print "\n" * 100


while x == 1:
    number1 = random.randrange(1,5)
    number2 = random.randrange(1,13)
    strength = number2/number1+10
    number3 = random.randrange(1,5)
    number4 = random.randrange(1,13)
    skill = number4/number3+10
    clear()
    print 'Hello and Welcome to the Character Charactaristics Machine'
    time.sleep(1)
    clear()
    qname = raw_input("What is your Character's name?:")
    time.sleep(1)
    clear()
    print "We will now determine", qname,"'s Charactaristics"
    time.sleep(0.5)
    print 'Calculating...'
    time.sleep(0.5)
    print 'Calculating...'
    time.sleep(0.5)
    print 'Calculating...'
    time.sleep(0.5)
    character = (qname,"'s skill level is",skill,"and strength level is" ,strength,)
    print character
    x = 2
    characterdata = open("test.txt", "w")
    characterdata.write(character)
    characterdata.close

我正在制作一个程序,您可以在其中输入角色名称,然后生成其强度和技能水平。我想要它,以便将角色的名称和技能/强度级别保存在某种数据库中。我试图让字符串“字符”(字符的详细信息)显示在 test.txt 文档中,但出现此错误:

Traceback (most recent call last):
  File "C:\Users\George\Documents\School Work\Characterisitcs of character the code.py", line 34, in <module>
    characterdata.write(character)
TypeError: expected a character buffer object

有帮助吗,谢谢

4

2 回答 2

1
character = (qname,"'s skill level is",skill,"and strength level is" ,strength,)

character变量是元组类型而不是字符串类型,这就是您收到错误的原因。

我想你的意思是这样。

character = qname + "'s skill level is" + str(skill) + "and strength level is" + str(strength)

上面创建了一个字符串类型变量。现在可以将此变量写入文件。

于 2013-10-31T17:52:22.073 回答
0

其他三种可能性:

character = ''.join(map(str, (qname,
                              "'s skill level is ",
                              skill,
                              ' and strength level is ',
                              strength,
                              )))
character = "%s's skill level is %s and strenght level is %s" % (qname, skill, strength)
character = "%(qname)s's skill level is %(skill)s and strength level is %(strength)s" \
            locals()

最后一个变体可能被认为是最好的,因为它适用于 i18n(它可以翻译,包括允许更改顺序)。

于 2013-12-14T14:24:08.750 回答