Strings are immutable

If you use [] operator on the left side of an assignment, with the intention of changing a character in a string you will get an error(exception).
>>> s = ‘I will be back’
>>>s[5] = B
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'str' object does not support item assignment
The value in this case is a string and the item is character we’re trying to assign. The reason for the error is that strings are immutable, which means that you can’t change existing string. The best you can do is create a new string that is variation on the original:
>>> s1 = s[0:5] + 'B' + s[6:]
>>> print s1
I wilB be back
In this example we’ve created new string which concatenates first 5 letters then adds 6-th letter and continues with from sixth letter until the end of the original string.

Nema komentara:

Objavi komentar