Course outline · 0% complete

0/32 lessons0%

Course overview →

String Methods

lesson 2-2 · ~12 min · 5/32

Methods: functions that belong to a value

In lesson 1-1 you met functions: named instructions like print() and type() that you call with parentheses around their input. A method is a function that belongs to one specific type of value, and you call it through a value with a dot: value.method(). upper is not a free-standing instruction, it exists only on strings, so you reach it through the string it will act on: "hi".upper() gives "HI".

Methods matter because real text is messy: users type stray spaces and random capitalization, files arrive half-formatted. Cleaning text before comparing or storing it is one of the most common jobs in working code, and these are the methods that do it:

MethodWhat it does
s.upper() / s.lower()new string in one case
s.strip()remove spaces/newlines from both ends
s.replace(old, new)swap every occurrence
s.count(x)how many times x appears
s.startswith(x) / s.endswith(x)True or False
s.title()Capitalize Each Word

One rule above all: strings are immutable, meaning they can never be changed in place. No method changes the original string. Every method hands you a new string, and if you do not save it in a variable, it is gone.

Code exercise · python

Run this. `strip()` cleans the ends first, then each method builds a new string from `clean`.

Code exercise · python

Run this real-world case. The user typed their email with stray spaces and capitals, so a direct comparison fails even though it is the same address. Normalizing both sides with strip() and lower() is the standard fix, which is why these two methods sit near every login form ever written.

Quiz

What does this print? ```python name = "ada" name.upper() print(name) ```

Code exercise · python

Your turn. Clean up the messy name: strip the spaces, then title-case it, and save the result in `name`. Print `name`, then print how many times the letter `a` (lowercase) appears in it.

Code exercise · python

One more. Clean `filename`: strip the spaces and lowercase it, saving the result in `clean`. Print `clean`, then print whether it ends with `.pdf`, then print `clean` with every underscore replaced by a dash.