Browser lab15 min+60 XP

String methods

Clean up messy text: change case, trim spaces and replace words.

0% done

Code runs right here in your browser. Nothing to install.

TASK 1

Learn it

Key idea

String methods return a new string, so store the result.

Key words
"   Dark Knight 99  ""Dark Knight 99""dark knight 99""dark_knight_99".strip().lower().replace(" ", "_")
Each method makes a new, cleaner string.

Strings come with lots of built-in methods. Case: upper(), lower(), title() and capitalize(). Trimming: strip() removes spaces from both ends (users often type extra spaces by accident), and lstrip() and rstrip() do one side.

text.replace("old", "new") swaps every match. Strings are immutable: methods give back a new string and never change the original, so store the result: name = name.strip().

You can chain methods: answer.strip().lower() cleans up user input in one go, so " YES " becomes "yes".

Real life linkWhen you sign up with " Nova@Example.com " the site quietly trims the spaces and lowers the capitals. Those are string methods.
Example code
raw = "   hELLo WoRLD   "
print(f"[{raw.strip()}]")
print(raw.strip().lower())
print(raw.strip().title())
msg = "I like cats. cats are great."
print(msg.replace("cats", "dogs"))
print(msg)
TASK 2

Try it yourself

+10 XP

Clean up the messy username so it has no spaces at the ends, is all lowercase, and uses underscores instead of spaces inside. It should print dark_knight_99.

Create a free account to start this lab

Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.

TASK 3

Capture the flag

+10 XP

Which method removes spaces from both ends of a string?

Create a free account to start this lab

Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.

HOMEWORK

Polite filter

+20 XP

Ask the user for a message. Replace the words stupid and dumb with *** (work on a lowercase copy), then print it with only the first letter capitalised. For That was a DUMB idea it prints That was a *** idea.

Create a free account to start this lab

Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.