[Tutor] Changing a string number to another number
Dave Angel
davea at davea.name
Wed Apr 15 14:36:17 CEST 2015
On 04/15/2015 08:21 AM, 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
A 'str' object is immutable, which means simply that you cannot modify
it in place. All you can do is create a new str object, and rebind your
variable to that new one. That means that there are a number of things
you cannot do directly to a string. One of them is modifying a slice,
as you're trying to do.
>
>
> datecode = "201504110102030405061"
> print datecode
> if datecode[20:21] == "1":
> datecode[20:21] = "0"
> print datecode
>
>
I can see that the first part of this is probably a standard datetime,
and might suggest you convert it to one, and modify that as needed. But
you're so far to the right that I have to figure you're doing some
custom encoding.
If you just want to replace a single character of a string, you could
use the construct:
datecode = datecode[:20] + "0" + datecode[21:]
If you need something fancier, perhaps you can generalize it.
--
DaveA
More information about the Tutor
mailing list