Working with Text · practice
Strings Return New Values
The
original = "quiet"
uppercase = original.upper()
print(original)
print(uppercase)
The output is:
quiet
QUIET
original still refers to "quiet". The method returned a separate uppercase string, which was assigned to uppercase.
Strings are immutable
Python strings are
An operation can produce a different string. A
message = "hello"
message = message.upper()
The variable message first refers to "hello", then to the new string "HELLO". The original string was not edited character by character.
This distinction will matter when you meet
Replace part of a string
The .replace() method returns a string with selected text replaced:
replace() receives two
the text to find;
the replacement text.
The original sentence remains "I like tea.". The returned string is "I like coffee.".
If the text to find does not occur, .replace() returns a string with the same characters. It does not report an error.
Do not ignore the return value
This call computes a new string but does not store or print it:
word = "cat"
word.replace("c", "h")
word still refers to "cat" afterward.
What will this program print?
word = "cat"
word.replace("c", "h")
print(word)Watch immutability happen
The exercise editor’s Step view lets you compare original and updated in the Locals panel before either print instruction runs. After the replacement, they contain "red balloon" and "blue balloon". The changed value is stored separately; the original string is still available.
Keep an original and an updated version
The starter program describes a red balloon.
Replace the empty string so updated is returned by calling .replace() on original. Change red to blue.
Keep original unchanged. The output must be:
Original: red balloon
Updated: blue balloon
This exercise checks an important habit: when a string operation returns a value you need,
Task
Use .replace() on original to create updated, changing red to blue.
Produce:
Original: red balloon
Updated: blue balloon
Use Step in the exercise editor. After the replacement original (red balloon) and updated (blue balloon) in Locals. Continue through the print instructions and watch the two lines appear.