【问题标题】:Pyt TypeError: Can't convert 'int' object to str implicitlyPyt TypeError:无法将“int”对象隐式转换为str
【发布时间】:2017-05-25 17:37:35
【问题描述】:

这是我的 python 程序代码,但我不能写marks.txt 我得到这样的错误它在x 之后显示 Python代码

file = open('marks.txt','w')
s1marks=0
s2marks=0
index=int(input("index:"))
if index != -1:
    s1marks=str(input("subject1marks:"))
    s2marks=str(input("subject2marks:"))
    x=str("index is"+index+s1marks+s2marks)
    file.write(x)
    index=int(input("next index:"))
    file.close()

错误

索引:10 主题1分:8 科目2分:5 回溯(最近一次通话最后): 文件“”,第 10 行,在 TypeError: 无法将 'int' 对象隐式转换为 str

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    您必须先将整数 index 转换为字符串。 Python 不明白你想连接 4 个字符串,因为有一个整数:

    x = "index is" + str(index) + s1marks + s2marks
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      在“正是它在锡上写的内容”类别中

      改变

      x=str("index is"+index+s1marks+s2marks)
      

      进入

      x = "index is" + str(index) + s1marks + s2marks
      

      但这不是我要做的唯一改变:

      • 您将整数0 分配给s1markss2marks 变量,然后您通过使用input() 分配string

      • 您还可以将input() 显式转换为str(),而根据定义,输入已经是一个字符串。

      • 在写入文件file.write(x) 后,您还需要另一个index,但您不会再次循环,这是因为您没有定义循环。如while

      • 处理文件,你应该使用with

      • 您不需要为 .write() 语句分配变量 x,除非您稍后对 x 执行其他操作,在此代码中您不需要这样做

      • 写入文件时需要换行符(这是我做的一个假设,可能你希望输出文件都在一行上),也就是'\n'

        李>
      • 你在你的代码中混合"',最好是选择一个并坚持下去

      • 不要在write()x= 中插入空格,这样可以提高输出文件的可读性。

      把它们放在一起:

      with open('marks.txt', 'w') as openfile:
          index = int(input('index:'))
          while index > 0:
              s1marks = input('subject1marks:')
              s2marks = input('subject2marks:')
              openfile.write('index is ' + str(index) + ' ' + s1marks + ' ' + s2marks + '\n')
              index = int(input('index:'))
      

      【讨论】:

        猜你喜欢
        • 2012-11-19
        • 1970-01-01
        • 1970-01-01
        • 2015-03-23
        • 2017-07-21
        • 1970-01-01
        • 2017-08-31
        • 2015-12-23
        相关资源
        最近更新 更多