Python字符串赋值错误发生在第二个循环上,但不是第一个

时间:2016-10-13 18:46:51

标签: python python-3.x typeerror

while循环的第一次运行很顺利:

hour_count = list('00/')
hours = 0

while hours < 24:                    #loop while hours < 24

    hour_count[1] = hours            #<- error occurs on this line
    hour_count = ''.join(hour_count) #convert to string
    ...
    hours += 1

然而,在第二个循环中,它给出了一个TypeError:'str'对象不支持项目赋值。目的是设置文件路径。

2 个答案:

答案 0 :(得分:1)

当您运行此行hour_count = ''.join(hour_count)时,您将hour_count的数据类型从列表更改为字符串。

因为字符串是不可变的,所以不能通过索引表示法修改一个字符(此行尝试执行此操作之前的行)。

我不完全确定你的目标是什么,但也许你想要附加到列表中。这些文档将有助于此。

https://docs.python.org/3.4/tutorial/datastructures.html

答案 1 :(得分:0)

您更改了类型;

# hour_count at this point is an array
hour_count[1] = hours

# The result of join is a string object
hour_count = ''.join(hour_count)

下次通过hour_count是一个字符串,你不能做“string [1] = ...”