Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我该如何防止;类型错误:Can';t转换为';int';隐式地反对str”;错误?_Python - Fatal编程技术网

Python 我该如何防止;类型错误:Can';t转换为';int';隐式地反对str”;错误?

Python 我该如何防止;类型错误:Can';t转换为';int';隐式地反对str”;错误?,python,Python,救命,不知道怎么做请救命! 我只是想说,在这之前有一些代码,我只是没有包括在内 sent = str(input("Please input a sentence:")) splitsent = sent.lower().split() deadno = [0] for count, v in enumerate(splitsent): if splitsent.count(v) < 2: deadno.append(max(deadno) + 1) else: dead

救命,不知道怎么做请救命! 我只是想说,在这之前有一些代码,我只是没有包括在内

sent = str(input("Please input a sentence:"))
splitsent = sent.lower().split()
deadno = [0]

for count, v in enumerate(splitsent):
if splitsent.count(v) < 2:
    deadno.append(max(deadno) + 1)
else:
    deadno.append(splitsent.index(v) +1)

deadno.remove(0)
print(deadno)
ofile = open ("Task2.txt","a+")
ofile.write("{s!s}\n{d!s}\n").format(s=sent, d=deadno)
ofile.write(sent + "\n" + deadno + "\n")
ofile.close()
sent=str(输入(“请输入一个句子:”)
splitsent=sent.lower().split()
死亡人数=[0]
对于计数,枚举中的v(splitsent):
如果已发送,则计数(v)<2:
deadno.append(最大(deadno)+1)
其他:
deadno.append(splitsent.index(v)+1)
死区编号。删除(0)
打印(死区编号)
ofile=open(“Task2.txt”、“a+”)
ofile.write(“{s!s}\n{d!s}\n”).format(s=sent,d=deadno)
ofile.write(已发送+“\n”+deadno+“\n”)
ofile.close()
编辑: 这是现在的代码,我现在得到的回溯是:

Traceback (most recent call last):
  File "H:\.Year 10\Year 10 Computing\A453\Task 2\Test 2.py", line 15, in <module>
    ofile.write("{s!s}\n{d!s}\n").format(s=sent, d=deadno)
AttributeError: 'int' object has no attribute 'format' 
回溯(最近一次呼叫最后一次):
文件“H:\.Year 10\Year 10 Computing\A453\Task 2\Test 2.py”,第15行,在
ofile.write(“{s!s}\n{d!s}\n”).format(s=sent,d=deadno)
AttributeError:“int”对象没有属性“format”

提前感谢,我愿意接受任何建议

在字符串中插入变量被认为是一种很好的做法

ofile.write("{s}\n{d}\n").format(s=sent, d=deadno))
请参阅以指定
send
deadno
的格式

如果出现相同类型的错误,可以按照注释中的建议,首先强制对变量调用str():

ofile.write("{s!s}\n{d!s}\n").format(s=sent, d=deadno))
格式
有点难处理(长文档,…),但它有强大的格式选项,可以使代码更易于阅读,更安全

另外,请编辑您的问题以添加变量分配(您向
send
deadno
提供值的行),也可以打印它们的类型和值,以便我们知道其中的内容:

for var in [send and deadno]:
    print(type(var))
    print(var)

发送的
deadno的类型是什么?您可能需要将它们转换为
str
因此
str(sent)
str(deadno)
您需要包含两个变量赋值。另外,编辑代码——缩进是错误的。最后,复制并粘贴对问题的完整回溯。请看@EdChum@joel goldstick你是一个传奇,有我的孩子!!!xpsent=“Hi there”1 2等待为什么????(老兄,这是个玩笑,我是个家伙)deadno不是int,它是一个包含int的列表。