Issue with saving into a Txt in python 3.3.2

纵然是瞬间 提交于 2019-12-13 08:14:41

问题


I have created a piece of code to save some data generated by my code into a txt file on my pc, however when ever i run the program i receive this error,

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

Im not sure what to do with this and need some help in figuring it out, this is my code;

 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()

I know its something to do with the 'str' definitions but I have been fiddling with it for like 30 mins now (yeah im a new programmer} and still to no avail so if someone could provide me with some help that would be great, thanks a lot


回答1:


Firstly, I'm assuming that the import statement isn't atually out-dented, just like that in the sample.

The error TypeError: Can't convert 'int' object to str implicitly essentially means that it can't add A to B, or in this case, an integer and a string. We can get round this by making

char1[1]="Strength now " + strh1

into:

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

This is just saying 'turn strh1 into a string before you add it. But after this I noticed a new error:

TypeError: 'str' object does not support item assignment.

This is because, at least in this case, you're treating the string as an array, mixed in with dictionary syntax (By the looks of it). I'm not sure what you're doing with the line

char1[1]="Strength now " + strh1

as it appears to me that you're trying to add an item to a dictionary which is not there, so I can only try to explain what's going wrong.

It's also worth noting that when you take an input as a string, it's not necessary to put it as foo = str(input("Bar: ")) as by default python takes inputs as strings. This means you would get the same result from foo = input("Bars: ").



来源:https://stackoverflow.com/questions/23137383/issue-with-saving-into-a-txt-in-python-3-3-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!