Working with text: tidy it up with a dot
Customers type in all sorts of ways: brownie, BROWNIE, bRoWnIe. Text comes with built-in tools that tidy it up, and you use them with a dot.
The big idea
A string has built-in tools called methods. Write a dot, the tool's name, and parentheses to get a changed copy of the text.
See it in code
.title() gives back the text with a capital letter at the start of each word. The dot connects the tool to the text it works on:
bake = "maple scone"
print(bake.title())Maple Scone
bake.title() handed back Maple Scone. The parentheses matter. They're what makes the tool run.
.upper() turns every letter into a capital. It's handy for a header that should stand out:
shop_name = "electric bakery"
border = "*~*"
print(f"{border} {shop_name.upper()} RECEIPT {border}")
print(f"Thanks for visiting the {shop_name.title()}!")*~* ELECTRIC BAKERY RECEIPT *~* Thanks for visiting the Electric Bakery!
The variable still holds electric bakery in small letters. Each tool gave back a changed copy and left the original alone.
.lower() makes every letter small. Use it on a typed answer before you check it, and capital letters stop causing trouble:
answer = input("Any nut allergy? (yes or no) ").lower()
if answer == "yes":
print("Thanks for telling us. We'll pick a nut-free bake.")
else:
print("Great, the brownies are fresh!")Any nut allergy? (yes or no) YES Thanks for telling us. We'll pick a nut-free bake.
The customer typed YES, and .lower() turned it into yes before the check. Without it, "YES" == "yes" would be false.
Tidying text is a big part of real programs. Any time a person types something, the program cleans it up first, so one small typing habit can't break a check.
Try it yourself
In the second program, swap .upper() and .title() and run it. Then try .lower() on the header. Which one looks best on a receipt?
The common mistake
Leaving off the parentheses. bake.title with no () doesn't run the tool. It prints something odd like <built-in method title...>. A method needs its parentheses to do its job.
What it unlocks
These tools shine inside f-strings, where a tidied value drops straight into a sentence. They also make input from a customer much safer to check.