Sub topic 3
Why Strings Are Immutable
Assume you can run Python scripts, use print(), and read simple statements.
Why strings are immutable
A Python str object is immutable, which means its characters cannot be changed after creation. An assignment binds a name to an object; it does not create a writable character box.
Indexing reads a character, but assigning to an index raises TypeError. To create changed text, build a new string.
word = "Python"
print(word[0])
print(word[1:])
try:
word[0] = "J"
except TypeError as error:
print(type(error).__name__)
word = "J" + word[1:]
print(word)Common string methods
String methods usually return a new string or another value. They do not modify the original string.
raw = " Hello, World "
clean = raw.strip().lower()
parts = clean.split(",")
joined = " | ".join(parts)
print(clean)
print(parts)
print(joined)
print("banana".replace("a", "o"))
print("banana".count("an"))Common errors include forgetting to save the returned value and calling a method on the wrong type.
Formatting output with f-strings
An f-string is a string literal prefixed with f. Expressions inside braces are evaluated when the string is created. Format specifiers control presentation.
name = "Ada"
total = 1234.5
items = 7
print(f"{name} owes ${total:,.2f} for {items:03d} items")
print(f"{total=}")The first format specifier adds a thousands separator and two decimal places. 03d pads an integer with zeroes.
Converting between strings and numbers
User input and file data commonly arrive as strings. Convert them before arithmetic, and handle invalid text with ValueError.
text = "42"
amount = int(text)
print(amount + 1)
try:
print(int("3.5"))
except ValueError:
print("Enter a whole number")
print(float("3.5"))
print(str(42) + "!")Unicode text versus bytes
A str stores Unicode text. bytes stores raw byte values, often for files or network protocols. Encode text to bytes and decode bytes back to text using the same character encoding.
text = "café"
data = text.encode("utf-8")
print(len(text))
print(data)
print(data.decode("utf-8"))Exercise
Why does text.replace("a", "o") not change text unless its result is assigned?
Show answer
Strings are immutable, so replace() creates and returns a new string.