Strings are immutable, meaning they can’t be modified. In this lesson, you’ll learn how to accomplish changing strings by generating a copy of the original string instead:
>>> s = 'mybacon' >>> s = 'f' Traceback (most recent call last): File "<input>", line 1, in <module> s = 'f' TypeError: 'str' object does not support item assignment
Here’s how to copy a string:
>>> s = 'mybacon' >>> s = s[:2] + 'f' + s[3:] >>> s 'myfacon' >>> s = 'mybacon' >>> s = s.replace('b', 'f') >>> s 'myfacon'
Become a Member to join the conversation.