Python - String String Update

Introduction

Python String is immutable sequence.

The immutable means that you cannot change a string in place:

S = 'test' 
>>> S[0] = 'x'                 # Raises an error! 
TypeError: 'str' object does not support item assignment 

To change a string, build and assign a new string.

Demo

S = 'test' 
S = S + 'TEST!'            # To change a string, make a new one 
print( S )
S = S[:4] + 'Burger' + S[-1] 
print( S )#   w w  w.ja  v  a2s  .c  om

Result

The following code assigns back the replaced string.

Demo

S = 'please' 
S = S.replace('pl', 't') 
print( S )

Result

String methods generate new string objects.