[Tutor] Changing a string number to another number

Peter Otten __peter__ at web.de
Wed Apr 15 14:50:57 CEST 2015


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
> 
> 
> datecode = "201504110102030405061"
> print datecode
> if datecode[20:21] == "1":
>      datecode[20:21] = "0"
> print datecode
> 
> 
> I have tried using the zero as an integer but still get the same error
> code. Any suggestion?

Strings in Python are "immutable", i. e. you cannot change them once they 
are created. Instead you have to construct a new string. In the general case 
you can get the same effect as replacing the character #n of an all-ascii 
string with

>>> s = "01234567890"
>>> n = 3
>>> s[:n] + "x" + s[n+1:]
'012x4567890'

In your case you want to replace the last character, so s[n+1:] is empty

>>> s = "201504110102030405061"
>>> n = 20
>>> s[n+1:]
''

and just

>>> s[:n] + "x"
'20150411010203040506x'

is sufficient. A word of warning: as you are using Python 2 you are actually 
manipulating bytes not characters when using the default string type. This 
may have ugly consequences:

>>> s = "ähnlich" # I'm using UTF-8
>>> print "ae" + s[1:]
ae�hnlich

Here the new string is not valid UTF-8 because in that encoding a-umlaut 
consists of two bytes and I'm only removing one of them.

A partial fix is to use unicode explicitly:

>>> s = u"ähnlich"
>>> print "ae" + s[1:]
aehnlich

But if you are just starting consider switching to Python 3 where unicode is 
the default string type.



More information about the Tutor mailing list