String is Immutable
In Python, strings are immutable, which means once a string is created, its individual characters cannot be changed or replaced using indexing or assignment.
This immutability ensures that string objects remain constant and secure in memory. Any attempt to modify a string directly will result in an error. If any modification is needed, a new string must be created based on the required changes.
Example of Invalid Modification:
name = "Peehu"
name[0] = "R" # This will raise an error
Output:
TypeError: 'str' object does not support item assignment
Explanation:
- Strings are immutable – their characters can't be altered directly using index positions.
- Here, we tried to change the first character
'P'to'R'. - Python does not allow direct item assignment for strings, so it raised a
TypeError.
Real-life Analogy:
Think of a string as a printed name on a paper. You can’t erase a single letter and write another; you need to print a new sheet with the correct name.
Correct Way (Create a New String):
name = "Vansh"
new_name = "Y" + name[1:]
print(new_name)
Output:
Yash
Explanation:
- We are not modifying the original string
namedirectly. - Instead, we created a new string by concatenating
"Y"withname[1:]. name[1:]returns all characters except the first one, and"Y"is added before it.- This way, the desired change is achieved without violating immutability.
Summary:
- Strings in Python are immutable – their characters cannot be changed after creation.
- Any modification must be done by creating a new string.
- Trying to change characters directly using indexing causes a TypeError.
- Use slicing and concatenation to build modified versions of strings.