Search code examples
pythonpython-3.xloopsvariablespraw

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


So I have this code:

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

and when I run it i get:

TypeError: 'str' object does not support item assignment

I make some variables with the names like answear0, answear1, etc. Then I need to write to replace the test text in these variables with a string:

"answear" [answeariteration] = str(answear)

It won't let me cycle thru every variable name.


Solution

  • I think you meant the line

    "answear" [answeariteration] = str(answear)
    

    to be

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

    But this is not a good way to do it. Instead of manipulation of variable names, you can use a dict. Maybe something like this:

    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
    

    And you can use a for loop instead of while.

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

    And you probably don't need to do the thread every loop, although I'm guessing about some things at this point.

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

    And now this is simple enough to be a comprehension

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

    Which could maybe be simplified to just

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

    if the comments were already strings. Not sure.

    And that could maybe be simplified to

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

    or even

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

    Since we were using numerical keys, starting from 0.

    In these cases, instead of using answer0, answer1, answer2, etc, you can use answer[0], answer[1], answer[2], etc.