String methods
Clean up messy text: change case, trim spaces and replace words.
Code runs right here in your browser. Nothing to install.
Learn it
String methods return a new string, so store the result.
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".
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)
Try it yourself
+10 XPClean 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.
Capture the flag
+10 XPWhich 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.
Polite filter
+20 XPAsk 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.