← Intro to programming with Python
Handy string tools
upper, lower, strip, replace and split.
Strings come with built-in tools called methods. You use one by writing a dot after the string: name.upper(). These tools save you from writing fiddly code yourself. Important: strings never change in place. A method gives you a NEW string, so you must store or print the result. The most useful ones: upper() and lower() change the case, strip() removes spaces from both ends, replace(old, new) swaps text, and split() breaks a string into a list of pieces.
raw = " Hello World "
clean = raw.strip()
print(clean.upper()) # HELLO WORLD
print(clean.replace("World", "Friends")) # Hello Friends
print("red,green,blue".split(",")) # ['red', 'green', 'blue']
print("one two three".split()) # ['one', 'two', 'three']split(",") breaks the text at each comma. split() with nothing inside breaks at spaces.
Common mistake: writing text.upper() on its own line and expecting text to change. It does not. Write text = text.upper() to keep the result.
lower() is the secret to checking answers people type: "Yes", "YES" and "yes" all become "yes".
Methods can be chained: " Hi ".strip().lower() gives "hi".