[Tutor] Changing a string number to another number [RESOLVED]

Ken G. beachkidken at gmail.com
Wed Apr 15 14:51:44 CEST 2015



On 04/15/2015 08:36 AM, Dave Angel wrote:
> 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.
>
Thank you, Dave. That did the trick. You were partly right about the
datetime as the first part is a date and following contains the lotto
numbers purchased for that date of a drawing. The last number in
the string indicates if a bonus multiplier for the ticket was purchased,
0 for no and 1 for yes.

Again, thanks.

Ken


More information about the Tutor mailing list