0
0
Pythonprogramming~5 mins

String immutability in Python

Choose your learning style9 modes available
Introduction

Strings cannot be changed after they are created. This helps keep data safe and predictable.

When you want to make sure a text value does not change by mistake.
When you share text data between different parts of a program safely.
When you want to use strings as keys in dictionaries or sets.
When you want to avoid bugs caused by changing text unexpectedly.
Syntax
Python
s = "hello"
s[0] = "H"  # This will cause an error

You cannot change a single character in a string directly.

To change text, you create a new string instead.

Examples
You cannot change a character inside a string.
Python
s = "hello"
# Trying to change a character causes error
# s[0] = "H"  # TypeError: 'str' object does not support item assignment
Create a new string by combining parts to 'change' text.
Python
s = "hello"
s = "H" + s[1:]
print(s)  # Output: Hello
Use string methods to create a new string with changes.
Python
s = "hello"
new_s = s.replace('h', 'H')
print(new_s)  # Output: Hello
Sample Program

This program shows that changing a string character directly causes an error. Then it shows how to create a new string with the desired change.

Python
s = "hello"
try:
    s[0] = "H"
except TypeError as e:
    print(f"Error: {e}")

# Correct way to change string
s = "H" + s[1:]
print(s)
OutputSuccess
Important Notes

Strings are like printed words on paper; you cannot erase a letter but you can write a new paper.

Always create a new string if you want to change text.

Summary

Strings cannot be changed after creation.

To change text, make a new string from parts or methods.

This helps keep your program safe and easy to understand.