TypeError:一元+“str”的操作数类型错误

2024-04-26 07:39:32 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我列出的清单:

nums= []
for n in range(10):
    thenums= random.randint(10,90)
    print(thenums, end= " ")
    nums.append(thenums)

现在我需要帮助分别写入每个整数,但是我在将列表中的每个数字写入文件的一行时遇到了一个问题。在

^{pr2}$

Tags: 文件in列表forrange数字整数random
1条回答
网友
1楼 · 发布于 2024-04-26 07:39:32

你的语法太离谱了。线

h.write[str(n), + '\n'] 

生成由两个元素组成的元组,str(n)和{};后者引发异常:

^{pr2}$

如果没有逗号,则可以正确连接数字和字符串:

>>> n = 42
>>> str(n) + '\n'
'42\n'

但是,您还试图使用h.write,就像它是一个列表或字典:

>>> h = open('/tmp/demo.txt', 'w')
>>> h.write['42\n']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'

使用(...)括号来调用某个内容;正确的表达式是:

h.write(str(n) + '\n')

相关问题 更多 >