In Python, strings are a fundamental data type used to store text. However, unlike lists or arrays, strings are immutable, meaning they cannot be changed once created. Learn more about string immutability in Python.
Apart from understanding string immutability, this page explores Python string modification technique using list, including why direct changes fail and how to work around immutability using methods like concatenation and list conversion.
By the end, you’ll understand practical ways to update strings while keeping your code efficient and error-free.
Real-World Analogy
A Python string is like a printed name badge. Once printed, it cannot be edited. To make a change, a new badge must be created.
String Immutability in Python
In Python, strings are immutable, meaning once a string is created, it cannot be changed directly. Any attempt to modify a string does not alter the original value.
Instead, Python creates a new string whenever a change is required. Because of this, operations that try to replace characters or slices will result in an error.
To better understand this behavior, let’s look at what happens when you try to modify a string directly.
Example: Attempting to Modify a String Directly
message = "Learn Python"
# Attempt to modify part of the string
message[6:] = "Programming" # Not allowed
Output:
TypeError: 'str' object does not support item assignment
Explanation: In this example, the code attempts to replace “Python” with “Programming” by assigning a new value to a slice of the string. Python strings do not allow direct modification of characters or slices. Any attempt to change part of a string results in a TypeError.
Instead, a new string must be created using techniques such as:
- string concatenation
- string methods (like replace(), upper(), lower())
- converting the string into a mutable structure like a list
Let’s start with one of the simplest techniques—string concatenation.
Using String Concatenation for Python String Modification
text = "Hello " + "World"
print(text)
Output:
Hello World
Explanation: Two strings are joined using the + operator, creating a new string without modifying the original.
While concatenation helps combine strings, it does not allow direct modification of specific characters. To achieve that, developers use a more flexible approach—converting strings into a list.
Basic Python String Modification Technique: Using a List
Since strings cannot be modified directly, developers often convert them into a list for simple changes.
Using a List for Character Modification
# Convert string to list
s = list("PYTHON")
# Modify a character
s[1] = "A"
# Convert back to string
modified = "".join(s)
print(modified)
Output:
PATHON
Explanation: The string is converted into a list, modified, and then joined back into a new string.