Pyt TypeError:无法转换' int'隐含地反对str

时间:2017-05-25 07:41:16

标签: python-3.x

这是我的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 subject1marks:8 subject2marks:5 Traceback(最近一次调用最后一次):   文件"",第10行,in TypeError:无法转换' int'隐含地反对str

2 个答案:

答案 0 :(得分:1)

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

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

我希望它有所帮助,

答案 1 :(得分:0)

类别“与锡上的内容完全相同

变化

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

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

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

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

  • 您还明确地将input()转换为str(),而输入根据定义已经是字符串。

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

  • 使用文件时,您应该使用with

  • 您不需要为x语句分配变量.write(),除非您稍后使用x执行其他操作,在此代码中您不会< / p>

  • 在写入文件时你需要做一个新的行字符(这是我做的假设,也许你想要输出文件全部在一行上),这是'\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:'))
相关问题