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

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

我正在进行数据分析,因为我想导航和显示时间,我正在使用 codeskulptor(python) 并且我使用此代码进行导航:

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))

我之前已经定义了所有变量,但我想出了错误:TypeError: 'str' does not support item assignmentin python。我该如何解决?

我正在为这个项目使用 simplegui 模块。

您将变量 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 一个包含两个值的 list

season = [1, 3]

并替换那些整数。