Code

Cleaning Up Text

Strings come with built-in tools called methods. You use them with a dot: text.method().

shout = "  Hello, Sailor!  "
print(shout.strip())    # "Hello, Sailor!"  (removes edge spaces)
print(shout.upper())    # "  HELLO, SAILOR!  "
print(shout.lower())    # "  hello, sailor!  "
print("pip the brave".title())   # "Pip The Brave"
print("dark night".replace("dark", "bright"))  # "bright night"

Methods can be chained. Each one works on the result of the one before:

print("  MiStY  ".strip().lower())   # "misty"

Methods never change the original string. Strings can't be changed at all (they're immutable). A method hands you a new string, so store it: name = name.strip().

Cleaning text like this is super common when handling what users type: extra spaces and random capitals are everywhere!

Assignment

A messenger scribbled the name of an island. Starting from raw:

  1. Set clean to raw with the spaces at both ends removed.
  2. Set calm to clean in all lowercase.
  3. Set fixed to calm with "misty" replaced by "sunny".
  4. Set banner to fixed in all UPPERCASE.