在python 3.3.2中保存到Txt的问题

时间:2014-04-17 15:35:21

标签: python string python-3.x save

我创建了一段代码,将我的代码生成的一些数据保存到我的电脑上的txt文件中,但是当我运行该程序时,我收到此错误,

Traceback (most recent call last):
  File "E:\CA2 solution.py", line 14, in <module>
    char1[1]="Strength now " +strh1
TypeError: Can't convert 'int' object to str implicitly

我不知道该怎么做,需要一些帮助来搞清楚,这是我的代码;

 import random

char1=str(input('Please enter a name for character 1: '))
strh1=((random.randrange(1,4))//(random.randrange(1,12))+10)
skl1=((random.randrange(1,4))//(random.randrange(1,12))+10)
print ('%s has a strength value of %s and a skill value of %s)'%(char1,strh1,skl1))


char2=str(input('Please enter a name for character 2: '))
strh2=((random.randrange(1,4))//(random.randrange(1,12))+10)
skl2=((random.randrange(1,4))//(random.randrange(1,12))+10)
print('%s has a strength value of %s and a skill value of %s'%(char1,strh1,skl1))

char1[1]="Strength now " +strh1

char1[2]="Skill now " +skl1

char2[1]="Strength now " +strh2
print()

char2[2]="Skill now " +skl1 
print()

myFile=open('CharAttValues.txt','wt')
for i in Char1:
    myFile.write (i)
    myFile.write ('\n')


for i in Char2:
    myFile.write (i)
    myFile.write('\n')
myFile.close()

我知道它与&#39; str&#39;定义,但我现在已经摆弄了30分钟(是的,我是一个新的程序员),但仍无济于事,所以如果有人可以给我一些很好的帮助,非常感谢

1 个答案:

答案 0 :(得分:2)

首先,我假设导入声明并非总体上凹陷,就像样本中那样。

错误TypeError: Can't convert 'int' object to str implicitly实质上意味着它无法将A添加到B,或者在这种情况下,是整数和字符串。我们可以通过制作

来解决这个问题
char1[1]="Strength now " + strh1

成:

char1[1]="Strength now " + str(strh1)

这只是说在添加之前将strh1转换为字符串。但在此之后我发现了一个新错误:

TypeError: 'str' object does not support item assignment

这是因为,至少在这种情况下,您将字符串视为数组,并与字典语法混合(通过它的外观)。我不确定你用线

做了什么
char1[1]="Strength now " + strh1

因为在我看来,你正试图将一个项目添加到不存在的字典中,所以我只能尝试解释出错的地方。

还值得注意的是,当您将输入作为字符串时,没有必要将其设置为foo = str(input("Bar: ")),因为默认情况下,python将输入作为字符串。这意味着您可以从foo = input("Bars: ")获得相同的结果。