TypeError:“str”不支持python中的项分配

2024-10-01 13:40:03 发布

您现在位置: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))

我之前已经定义了所有的变量,并且在python中出现了错误:TypeError: 'str' does not support item assignment。我怎么解决这个问题?在

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


Tags: key代码ifdef时间erroryearglobal
1条回答
网友
1楼 · 发布于 2024-10-01 13:40:03

将变量season设置为字符串:

season = '1-3'

然后尝试指定特定的索引:

^{pr2}$

你得到这个错误是因为字符串对象是不可变的。在

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

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

替换最后一个字符和

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

替换第一个。在

也许您应该将seasona列表包含两个值:

season = [1, 3]

然后替换这些整数。在

相关问题 更多 >