TypeError: 'str' does not support item assignment in python

2.4k Views Asked by At

I'm working on data analysis as I want to navigate and show the time, I'm using codeskulptor(python) and I used this code to navigate:

def keydown(key):
    global season, year, navtime
    if key == 37:
        navtime += 1
        season[2] = str(int(season[2]) - 3) # error
        if int(season[0] - 3) <= 0:
            year = str(int(year) - 1)
            season = '10-12' 
        else:
            season[0] = str(int(season[0] - 3))
    if key == 39:
        navtime -= 1
        season[2] = str(int(season[2]) + 3) # error
        if int(season[0] + 3) >= 12:
            year = str(int(year) + 1)
            season = '1-3'
        else:
            season[0] = str(int(season[0] + 3))

I already previously defined all the variables and I came up with the error: TypeError: 'str' does not support item assignmentin python. How do I fix this?

I'm using the simplegui module for this project.

1

There are 1 best solutions below

0
On BEST ANSWER

You set the variable season to a string:

season = '1-3'

then try to assign to specific indices:

season[2] = str(int(season[2]) - 3)

You get that error because a string object is immutable.

If you wanted to replace characters in the string, you'll need to build a new string object:

season = season[:-1] + str(int(season[2]) - 3)

to replace the last character and

season = str(int(season[0] - 3)) + season[1:]

to replace the first.

Perhaps you should instead make season a list of two values:

season = [1, 3]

and replace those integers.