Strings are Immutable

Strings are Immutable

my_var = 'abcdefg'

# To replace a with 1:
my_var[0] = "1" # This does not work, it will generate error:
# 'str' object does not support item assignment

# In order for it to work you will have to replace the whole string:
my_var = '1bcdefg'

# To do this programmatically you will have to:
my_var[1:] # Capture everything from the 2nd character
my_var = '1' + my_var[1:] # Add 1 to the captured string and reassign the variable

Last updated