简体   繁体   中英

Python string assignment error occurs on second loop, but not first

The first run-through of the while loop goes fine:

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

However, upon the second loop, it gives a TypeError: 'str' object does not support item assignment. The purpose is to set a file path.

When you run this line hour_count = ''.join(hour_count) , you're changing the data type of hour_count from a list to a string.

Because strings are immutable, you can't modify one character via the index notation (the line before this line attempts to do that).

I'm not totally sure what your goal is, but perhaps you're looking to append to the list. These docs will help with that.

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

You changed the type;

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

Next time through hour_count is a string and you can't do "string[1] = ..."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM