Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Change a string

  • immutable

In Python strings are "immutable", meaning you cannot change them. You can replace a whole string in a variable, but you cannot change it.

In the following example we wanted to replace the 3rd character (index 2), and put "Y" in place. This raised an exception

text = "abcd"
print(text)     # abcd

text[2] = 'Y'

print("done")
print(text)
abcd
Traceback (most recent call last):
  File "string_change.py", line 4, in <module>
    text[2] = 'Y'
TypeError: 'str' object does not support item assignment

Replace part of a string

  • Strings in Python are immutable - they never change.