0%

Working with Text · practice

Strings Return New Values

The you have used so far return strings. They do not change the original string .

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 . Once a particular string value exists, its characters do not change in place.

An operation can produce a different string. A can then be reassigned to that returned value:

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 in Chapter 6, because a list is and can change in place.

Replace part of a string

The .replace() method returns a string with selected text replaced:

Try it

replace() receives two :

  1. the text to find;

  2. 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, that value somewhere.

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 , compare original (red balloon) and updated (blue balloon) in Locals. Continue through the print instructions and watch the two lines appear.