Lesson 17 · 17 of 20
String methods · Python
Clean up and transform text in Python with strip, split, join, lower, upper, replace, find and count, tidying a list of ingredients.

Strings have methods too. None of them changes the original string (strings cannot be modified): they all return a new string. strip() removes the spaces at the start and the end; the square brackets in the output show that the ones in the middle are still there.
split(",") cuts the string at every comma and returns a list of pieces, still with stray spaces and mixed capitals.
The loop cleans each piece by chaining methods: part.strip().lower() first removes the spaces and then turns the result into lower case. Each clean piece is added to items with append().
join() does the opposite of split(): it glues a list into one string, putting the text it is called on between the items, here " | ".
With the recipe title, upper() turns it into capitals, title() capitalises each word and replace() swaps one piece of text for another. startswith() answers True or False, count() counts how many times something appears and find() tells you where it starts (or -1 if it is not there).
Code · main.py
# Ingredients typed in a hurry: spaces and capitals all over.raw = " tomato, Onion ,garlic, PEPPER "# strip() removes the spaces at both ends.clean = raw.strip()print(f"[{clean}]")# split() cuts a string into a list, at each comma.parts = clean.split(",")print(parts)# Tidy each piece: no spaces and in lower case.items = []for part in parts: items.append(part.strip().lower())print(items)# join() glues a list into one string.print(" | ".join(items))title = "salsa verde recipe"print(title.upper())print(title.title())print(title.replace("verde", "roja"))print("Starts with 'salsa'?", title.startswith("salsa"))print("How many 'e':", title.count("e"))print("Where is 'recipe'?", title.find("recipe"))Output · python3 main.py
[tomato, Onion ,garlic, PEPPER] ['tomato', ' Onion ', 'garlic', ' PEPPER'] ['tomato', 'onion', 'garlic', 'pepper'] tomato | onion | garlic | pepper SALSA VERDE RECIPE Salsa Verde Recipe salsa roja recipe Starts with 'salsa'? True How many 'e': 4 Where is 'recipe'? 12
Key points
- String methods return a new string.
strip()removes spaces from both ends.text.split(",")gives a list;", ".join(items)glues it back.lower(),upper()andtitle()change the case.replace(),find()andcount()search and replace.
Exercise
Ask for a sentence with input() and print how many words it has, its longest word, and the sentence with every word reversed.