Are strings mutable in Python, and how do you change a character in one?
Strings are immutable, so s[0] = "x" raises TypeError. To change one, build a new string using slicing, replace(), or join over a list of characters.
Explain it simply
A string is like a sentence printed in a textbook. You cannot rub out one letter and write another; you have to print a fresh copy with the change. Methods such as upper() and replace() never edit the original, they return a new string.
Immutability is also why strings can be dictionary keys and why Python can safely reuse them behind the scenes.
Example
s = "cat"
try:
s[0] = "b"
except TypeError:
print("cannot assign") # Output: cannot assign
t = "b" + s[1:]
print(t) # Output: bat
print(s) # Output: cat
print(s.replace("c", "r")) # Output: rat
chars = list("cat")
chars[0] = "h"
print("".join(chars)) # Output: hatWhat to say in the interview
"Strings are immutable. Any operation that looks like a change returns a new string, and the original is untouched. To edit characters I use slicing and concatenation, replace(), or convert to a list, modify and join back. Immutability makes strings hashable and thread-safe to share."
Common mistakes
- Calling
s.upper()and ignoring the result, expectingsto change.