我正在进行数据分析,因为我想导航并显示时间,我正在使用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模块。
答案 0 :(得分:3)
您将变量season
设置为字符串:
season = '1-3'
然后尝试分配给特定的指数:
season[2] = str(int(season[2]) - 3)
您收到该错误,因为字符串对象是不可变的。
如果您想替换字符串中的字符,则需要构建 new 字符串对象:
season = season[:-1] + str(int(season[2]) - 3)
替换最后一个字符和
season = str(int(season[0] - 3)) + season[1:]
替换第一个。
也许您应该使season
成为两个值的列表:
season = [1, 3]
并替换那些整数。