2016-04-12 51 views
-2

帮助,没有线索如何做到这一点,请帮助! 只是说有一些代码在此之前,我只是还没有包括它如何防止“TypeError:无法将'int'对象隐式转换为str”错误?

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

编辑: 这是现在的代码,我现在明白了回溯是:

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' 

在此先感谢,我愿意接受任何建议

+1

什么是“发送”和“死亡”的类型?你可能需要将它们转换为'str',以便'str(发送)'和'str(死亡)' – EdChum

+2

你需要包含两个变量赋值。另外,编辑你的代码 - 缩进是错误的。最后,将你的完整追溯复制并粘贴到你的问题上。另请参阅@EdChum。 –

+0

@ joel goldstick你是一个传奇有我的宝贝! XP –

回答

2

使用format在字符串中插入变量被认为是很好的做法。

ofile.write("{s}\n{d}\n").format(s=sent, d=deadno)) 

format examples指定格式senddeadno

如果你得到同样的错误,你可能会迫使str的()调用中的变量第一次作为一个评论所说:

ofile.write("{s!s}\n{d!s}\n").format(s=sent, d=deadno)) 

format有点难以接近(长文档, ...),但它具有强大的格式选项,它可以使你的代码更容易阅读和更安全。

另外,请编辑您的问题补充变量赋值(其中你senddeadno提供值线),也许还打印其类型和价值,只是让我们知道什么是在那里:

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

我已更新但仍出现错误 –

+0

deadno不是int,它是一个包含整数的列表。 –

相关问题