Concept Flow - String immutability
Create string s = "hello"
Try to change s[0
Error: strings cannot be changed
Create new string s = "Hello"
Use new string s
END
Strings cannot be changed once created. To modify, you make a new string instead.
s = "hello" s[0] = 'H' # Error s = "Hello" # New string print(s)
| Step | Action | Code Line | Result | Notes |
|---|---|---|---|---|
| 1 | Create string s | s = "hello" | s = "hello" | String s holds 'hello' |
| 2 | Try to change s[0] | s[0] = 'H' | TypeError | Strings are immutable, error raised |
| 3 | Create new string s | s = "Hello" | s = "Hello" | New string assigned to s |
| 4 | Print s | print(s) | Hello | Output is the new string |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| s | undefined | "hello" | Error (no change) | "Hello" | "Hello" |
String immutability in Python: - Strings cannot be changed once created. - Trying to change a character causes an error. - To modify, create a new string and assign it. - Example: s = "hello"; s = "Hello" - Always remember: strings are fixed after creation.