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'
If you’d like to learn more, then check out How to Replace a String in Python.
Uğur on Jan. 27, 2021
It seems that you are big fan of bacon. Don’t you? I strongly suggest you that use a different word something sound nice.