【问题标题】:Issue with saving into a Txt in python 3.3.2在 python 3.3.2 中保存到 Txt 的问题
【发布时间】:2014-06-01 23:24:21
【问题描述】:

我创建了一段代码,将我的代码生成的一些数据保存到我电脑上的 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()

我知道它与“str”定义有关,但我已经摆弄了大约 30 分钟(是的,我是一个新程序员},但仍然无济于事,所以如果有人可以为我提供一些帮助太好了,非常感谢

【问题讨论】:

    标签: python string python-3.x save


    【解决方案1】:

    首先,我假设 import 语句实际上并没有像示例中那样突出。

    错误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: ") 获得相同的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多