这是我的代码:
import random
ch1=input("Please enter the name of your first character ")
strch1=(((random.randint(1,12)//(random.randint(1,4))))+10)
sklch1=(((random.randint(1,12)//(random.randint(1,4))))+10)
print("The strength value of "+ch1+" is:")
print (strch1)
print("and the skill value of "+ch1+" is:")
print (sklch1)
ch2=input("Please enter the name of your second character ")
strch2=(((random.randint(1,12)//(random.randint(1,4))))+10)
sklch2=(((random.randint(1,12)//(random.randint(1,4))))+10)
print("The strength value of "+ch2+" is:")
print (strch2)
print("and the skill value of "+ch2+" is:")
print (sklch2)
myFile = open("CharacterSkillAttributes.txt", "wt")
myFile.write("The attributes of "+ch1+" are: /n")
myFile.write("Strength: "+strch1+"/n")
myFile.write("Skill: "+sklch1+"/n")
myFile.write("The attributes of "+ch2+" are: /n")
myFile.write("Strength: "+strch2+"/n")
myFile.write("Skill: "+sklch2+"/n")
myFile.close()
这是错误:
Traceback (most recent call last):
File "E:\Computing Science\Computing science A453\Task 2\task 2 mostly working (needs 'save to file').py", line 22, in <module>
myFile.write("Strength: "+strch1+"/n")
TypeError: Can't convert 'int' object to str implicitly
我不想过多地更改代码(除非我真的需要),只需要解决这个问题。
答案 0 :(得分:5)
使用字符串格式来消除错误:
file.write('Strength: {0}\n'.format(sklch1))
显然,当您使用sklch2
写入文件时,您必须执行相同操作。
答案 1 :(得分:1)
你应该从你的整数变量中创建一个字符串:
myFile.write("Strength: " + str(strch1) + "/n")
或建议Alex使用str.format()
。
答案 2 :(得分:0)
错误消息确切地告诉您,strch1
是一个int,您无法直接将其与字符串连接。
你可以做到
file.write('Strength: %s\n' % (sklch1))