In "Python: Sequences
" I said:
|A string is a list of characters, like "Hello World!". A list is simply a list of any sort of data element, in many other programming languages known as array. A tuple is like a list, but not changeable. |
What I forgot to mention here is: a string is not changeable as well.
Thus, assume you have a string "Hello World." What if you want to change the last character of this string to "!" to get "Hello World!" ? How would you do this ? Or as a more practical example assume you have a string "/tmp/somedir/" and you want to remove the last slash. How would you achieve this ?
Something like this won't work in Python:
|>>> str = "Hello World."
>>> str[-1] = "!"
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
str[-1] = "!"
TypeError: 'str' object does not support item assignment
Anyone any idea ?
2 blog comments below
I guess you could do something like this
|str = str[:-1] + '!' |
Not sure if there are better ways.
Peterssidan, you are perfectly right.
We can verify this by using my Python Expression Evaluator and typing in this expression:
|"Hello World."[:-1]+"!" |