String Methods
upper, strip, replace, split, join, and friends.
5 minute read
Big idea
A method is a function that belongs to a value. Strings come with dozens: text.upper(), text.strip(), text.replace(...). Each one returns a new string.
Calling a method
Put a dot after the value, then the method name and parentheses:
name = "ada lovelace"
print(name.upper())
print(name.title())
print(name.capitalize())
print(name)output
ADA LOVELACE
Ada Lovelace
Ada lovelace
ada lovelaceRun and edit it in the app.
The last line proves it: name didn't change. Strings are immutable, so methods hand you a new string. To keep it, assign it: name = name.title().
The ones you'll use most
| Method | Does | Example → result |
|---|---|---|
.upper() / .lower() | change case | "Hi".lower() → "hi" |
.strip() | remove spaces at both ends | " hi ".strip() → "hi" |
.replace(a, b) | swap every a for b | "a-b-c".replace("-", "") → "abc" |
.split(sep) | cut into a list | "a,b".split(",") → ["a", "b"] |
sep.join(list) | glue a list together | "-".join(["a", "b"]) → "a-b" |
.find(x) | index of x, or -1 | "hello".find("l") → 2 |
.count(x) | how many times | "banana".count("a") → 3 |
.startswith(x) / .endswith(x) | True/False | "photo.png".endswith(".png") → True |
.isdigit() / .isalpha() | all digits / all letters? | "42".isdigit() → True |
raw = " Hello, World "
clean = raw.strip()
print(clean)
print(clean.lower().replace("world", "Python"))
print(clean.count("l"))What does it print? Show the answer
Hello, World
hello, Python
3Run and edit it in the app.
The second line chains methods: .lower() makes a new string, and .replace(...) runs on that.
Watch it
split and join
split and join are opposites — one breaks a string apart, the other glues pieces together:
sentence = "the quick brown fox"
words = sentence.split()
print(words)
print(len(words))
print("_".join(words))output
['the', 'quick', 'brown', 'fox']
4
the_quick_brown_foxRun and edit it in the app.
split() with nothing inside splits on any run of spaces. The square brackets are a list — a whole module on those is coming.
The in operator
in asks "does this appear anywhere inside?":
print("cat" in "concatenate") # True
print("dog" in "concatenate") # False
message = "watch out"
message.upper()
print(message + "!")output
WATCH OUT!Run and edit it in the app.
s = 'hi'. After the line s.upper() on its own, what is s?
Think of it like
A photocopier with filters. You put the page in, choose "upper case" or "remove spaces", and out comes a new copy. The original page is untouched.
Key terms
- Method — A function attached to a value, called with a dot:
s.upper(). - Chaining — Calling one method on the result of another.
- in — Checks whether one string appears inside another.
Check yourself
What does " hi ".strip() give?
What does "-".join(["a", "b", "c"]) give?
Why doesn't name.upper() on its own change name?