TypeError: 'str' object does not support item assignment when trying to run thru variables to write to them

TypeError: 'str' object does not support item assignment when trying to run thru variables to write to them

所以我有这个代码:

answeariteration = 0
while answeariteration < int(numberofanswears):
    thread = reddbot.submission(url = str(submissionurl))
    globals()["answear" + str(answeariteration)] = "test"

    answear = thread.comments[answeariteration]

    "answear" [answeariteration] = str(answear)
    answeariteration += 1

当我 运行 我得到:

TypeError: 'str' object does not support item assignment

我创建了一些变量,名称为 answear0、answear1 等。然后我需要编写将这些变量中的测试文本替换为字符串:

"answear" [answeariteration] = str(answear)

它不会让我循环遍历每个变量名。

我认为你的意思是行

"answear" [answeariteration] = str(answear)

成为

globals()["answear"+str(answeariteration)] = str(answear)

但这不是一个好的方法。您可以使用字典来代替操作变量名。也许是这样的:

answer = {}

answer_iteration = 0
while answer_iteration < int(numberofanswers):
    thread = reddbot.submission(url=str(submissionurl))
    answer[answer_iteration] = str(thread.comments[answer_iteration])
    answer_iteration += 1

您可以使用 for 循环代替 while

answer = {}

for answer_iteration in range(numberofanswers):
    thread = reddbot.submission(url=str(submissionurl))
    answer[answer_iteration] = str(thread.comments[answer_iteration])

而且你可能不需要在每个循环中都执行线程,尽管此时我在猜测一些事情。

answer = {}
thread = reddbot.submission(url=str(submissionurl))
for answer_iteration, comment in enumerate(thread.comments):
    answer[answer_iteration] = str(comment)

现在这很简单,可以理解

thread = reddbot.submission(url=str(submissionurl))
answer = {i: str(comment) for i, comment in enumerate(thread.comments)}

也许可以简化为

thread = reddbot.submission(url=str(submissionurl))
answer = dict(enumerate(thread.comments))

如果评论已经是字符串。不确定。

这也许可以简化为

thread = reddbot.submission(url=str(submissionurl))
answer = list(thread.comments)

甚至

answer = list(reddbot.submission(url=str(submissionurl)).comments)

由于我们使用的是数字键,因此从 0 开始。

在这些情况下,您可以使用 answer[0]answer[1]、[=26] 而不是 answer0answer1answer2 等=],等等