[Tutor] Changing a string number to another number

Steven D'Aprano steve at pearwood.info
Wed Apr 15 15:09:25 CEST 2015


On Wed, Apr 15, 2015 at 08:21:33AM -0400, Ken G. wrote:
> When running the following code, I get the following
> error code:
> 
> 201504110102030405061
> Traceback (most recent call last):
>   File "Mega_Millions_Tickets_Change.py", line 11, in <module>
>     datecode[20:21] = "0"
> TypeError: 'str' object does not support item assignment

Try this:

datacode = datacode[:20] + "0" + datacode[21:]


This is called "slicing". We take a slice of the string, from the start 
up to just before position 20; "0"; and a slice from position 21 to the 
end of the string. The three pieces are then concatenated together, 
giving a new string.



-- 
Steve


More information about the Tutor mailing list