0

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.

4

1 回答 1

3

您将变量设置season为字符串:

season = '1-3'

然后尝试分配给特定的索引:

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

您会收到该错误,因为字符串对象是不可变的。

如果要替换字符串中的字符,则需要构建一个的字符串对象:

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

替换最后一个字符和

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

替换第一个。

也许您应该列出两个值season

season = [1, 3]

并替换那些整数。

于 2015-08-09T03:36:56.393 回答