
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:
- Set
cleantorawwith the spaces at both ends removed. - Set
calmtocleanin all lowercase. - Set
fixedtocalmwith"misty"replaced by"sunny". - Set
bannertofixedin all UPPERCASE.
A messenger scribbled the name of an island. Starting from raw:
- Set
cleantorawwith the spaces at both ends removed. - Set
calmtocleanin all lowercase. - Set
fixedtocalmwith"misty"replaced by"sunny". - Set
bannertofixedin all UPPERCASE.
main.py Python sleeping
Press Run to try your code, then Check to test it.