class MutableString:
def __init__(self, initial):
self.chars = list(initial) # store characters in a list for mutability
def set_char(self, index, char):
if 0 <= index < len(self.chars):
self.chars[index] = char # directly change character
def __str__(self):
return ''.join(self.chars)
def immutable_string_change(s, index, char):
# Cannot change string directly, create new string
if 0 <= index < len(s):
return s[:index] + char + s[index+1:]
return s
# Driver code
original = 'hello'
# Immutable string attempt
try:
# This will raise an error in Python
# original[1] = 'a'
pass
except TypeError:
print('Cannot change immutable string directly')
new_string = immutable_string_change(original, 1, 'a')
print('Original immutable:', original)
print('New immutable:', new_string)
# Mutable string example
mutable = MutableString('hello')
mutable.set_char(1, 'a')
print('Mutable changed:', mutable)self.chars = list(initial) # store characters in a list for mutability
store string as list to allow changes
self.chars[index] = char # directly change character
directly update character at index
return s[:index] + char + s[index+1:]
create new string with changed character
Original immutable: hello
New immutable: hallo
Mutable changed: hallo