Kodeclik Blog
About
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.
Popular Classes
Scratch Coding
Minecraft Coding
TinkerCAD
Roblox Studio
Python for Kids
Javascript for Kids
Pre-Algebra
Geometry for Kids
Copyright @ Kodeclik 2024. All rights reserved.
Did you know that a Python string is not mutable? Heh? - you ask. What does that mean?
A mutable object or thing is one that can be changed or altered after its creation. An immutable object or thing is one that cannot be changed or modified once it has been created.
Consider the following code:
In the first two lines, we create a string variable mystring containing "Hello". Then we use string indexing `` to access the first character, which is 'H'. This operation works perfectly fine because reading or accessing characters from a string is always allowed. The next two lines (specifically, the first of these next two lines) will cause an error:
This error demonstrates why strings are immutable in Python. When we try to modify the first character of the string from 'H' to 'J', Python raises a TypeError with the message "'str' object does not support item assignment". This happens because Python strings are immutable - once created, they cannot be modified in place. The second print statement never executes because the program stops at the error.
If you want to make this kind of change, you need to create a new string instead. Here's how you could do it:
The output now will be:
This creates an entirely new string (by recreating “mystring”) rather than modifying the existing one.
Because strings are immutable, string methods typically create a new string object. Consider:
The output will be:
As you can see in the first section, string methods create new strings rather than modifying the original. The code creates a string variable original with the value "Hello" and then calls the upper() method to create a new string with all uppercase letters. When we print both strings, we see that original remains unchanged as "Hello" while uppercase contains the new string "HELLO". This illustrates that string methods always return new string objects rather than modifying the existing one.
The second section shows how string concatenation creates new objects in memory. We start with a string text containing "Hello" and print its memory address using the id() function. When we concatenate " World" to text, Python creates an entirely new string object with the combined value "Hello World". The second id() print statement shows a different memory address, proving that concatenation created a new string object rather than modifying the original one.
The third section demonstrates that Python strings don't support slice assignment. The code attempts to replace two characters in the string "Python" using slice notation [2:4], but this operation raises a TypeError. The try-except block catches this error and prints the error message "'str' object does not support item assignment". This further reinforces that strings in Python are immutable and cannot be modified through any means, including slice notation.
Ok, now that we ensured that strings are immutable is there a way to convert them to a different form that is mutable? That is what we are looking at in this blogpost!
The most direct way to get a mutable string-like object is to convert it to a bytearray. Consider the below code:
This program creates a mutable sequence of bytes that you can modify in place. The process works by first converting the string to a bytearray, which is mutable. Then we modify the first character by using ord('J') which gives us the ASCII/Unicode value of 'J'. Finally, we decode the bytearray back to a string. This approach works because bytearrays are mutable, allowing us to change individual bytes, unlike strings which are immutable.
The output wil be:
In this approach we convert the Python string to a mutable data structure by converting it into a list:
This method works by first converting the string to a list of individual characters, which is mutable. We can then modify any character in the list by its index. Finally, we use the join() method to convert the list back into a string. This approach is more straightforward than using bytearray as it doesn't require encoding and decoding steps.
The output will be:
In summary, it is crucial to understand that Python strings themselves are fundamentally immutable, which means:
The immutability of strings in Python is a design choice that provides benefits for hashing, performance optimization, and safety.
To convert strings to mutable data structures:
Enjoy this blogpost? Want to learn Python with us? Sign up for 1:1 or small group classes.
mystring = 'Hello'
print(mystring[0])
mystring[0] = 'J'
print(mystring[0])
H
Traceback (most recent call last):
File "main.py", line 4, in <module>
mystring[0] = 'J'
TypeError: 'str' object does not support item assignment
mystring = 'Hello'
print(mystring[0])
mystring = 'J' + mystring[1:] # Creates a new string "Jello"
print(mystring[0])
H
J
# String methods create new strings
original = "Hello"
uppercase = original.upper()
print(f"Original: {original}")
print(f"New string: {uppercase}")
# String concatenation creates a new string object
text = "Hello"
print(f"Original ID: {id(text)}")
text = text + " World"
print(f"New ID: {id(text)}")
# Attempting to modify using slice notation
name = "Python"
try:
name[2:4] = "xx"
except TypeError as e:
print(f"Error: {e}")
Original: Hello
New string: HELLO
Original ID: 139739651686704
New ID: 139739651688048
Error: 'str' object does not support item assignment
greeting = "Hello!"
# Convert to bytearray
mutable_greeting = bytearray(greeting.encode("utf-8"))
# Change 'H' to 'J'
mutable_greeting[0] = ord('J')
# Convert back to string
new_greeting = mutable_greeting.decode("utf-8")
print(new_greeting)
Jello!
# Convert string to list
greeting = "Hello!"
char_list = list(greeting)
# Modify the first character
char_list[0] = 'J'
# Join back into string
new_greeting = ''.join(char_list)
print(new_greeting)
Jello!