On 04/15/2015 08:50 AM, Peter Otten wrote:
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.

Thank you, Peter. That would be something for me to consider.
Alas, I am still using Python 2.7.6 but do have it on standby.

Again, thanks.

Ken
_______________________________________________
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to